Coverage Report

Created: 2023-11-19 01:18

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.90 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ                   https://dearimgui.com/faq
11
// - Getting Started       https://dearimgui.com/getting-started
12
// - Homepage              https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/6897 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
// - Tests & Automation    https://github.com/ocornut/imgui_test_engine
19
20
// For first-time users having issues compiling/linking/running/loading fonts:
21
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
23
24
// Copyright (c) 2014-2023 Omar Cornut
25
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
26
// See LICENSE.txt for copyright and licensing details (standard MIT License).
27
// This library is free but needs your support to sustain development and maintenance.
28
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
29
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Sponsors
30
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
31
32
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
33
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
34
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
35
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
36
// to a better solution or official support for them.
37
38
/*
39
40
Index of this file:
41
42
DOCUMENTATION
43
44
- MISSION STATEMENT
45
- CONTROLS GUIDE
46
- PROGRAMMER GUIDE
47
  - READ FIRST
48
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
49
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
50
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
51
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
52
- API BREAKING CHANGES (read me when you update!)
53
- FREQUENTLY ASKED QUESTIONS (FAQ)
54
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
55
56
CODE
57
(search for "[SECTION]" in the code to find them)
58
59
// [SECTION] INCLUDES
60
// [SECTION] FORWARD DECLARATIONS
61
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
62
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
63
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
64
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
65
// [SECTION] MISC HELPERS/UTILITIES (File functions)
66
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
67
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
68
// [SECTION] ImGuiStorage
69
// [SECTION] ImGuiTextFilter
70
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
71
// [SECTION] ImGuiListClipper
72
// [SECTION] STYLING
73
// [SECTION] RENDER HELPERS
74
// [SECTION] INITIALIZATION, SHUTDOWN
75
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
76
// [SECTION] INPUTS
77
// [SECTION] ERROR CHECKING
78
// [SECTION] LAYOUT
79
// [SECTION] SCROLLING
80
// [SECTION] TOOLTIPS
81
// [SECTION] POPUPS
82
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
83
// [SECTION] DRAG AND DROP
84
// [SECTION] LOGGING/CAPTURING
85
// [SECTION] SETTINGS
86
// [SECTION] LOCALIZATION
87
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
88
// [SECTION] DOCKING
89
// [SECTION] PLATFORM DEPENDENT HELPERS
90
// [SECTION] METRICS/DEBUGGER WINDOW
91
// [SECTION] DEBUG LOG WINDOW
92
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
93
94
*/
95
96
//-----------------------------------------------------------------------------
97
// DOCUMENTATION
98
//-----------------------------------------------------------------------------
99
100
/*
101
102
 MISSION STATEMENT
103
 =================
104
105
 - Easy to use to create code-driven and data-driven tools.
106
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
107
 - Easy to hack and improve.
108
 - Minimize setup and maintenance.
109
 - Minimize state storage on user side.
110
 - Minimize state synchronization.
111
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
112
 - Efficient runtime and memory consumption.
113
114
 Designed primarily for developers and content-creators, not the typical end-user!
115
 Some of the current weaknesses (which we aim to address in the future) includes:
116
117
 - Doesn't look fancy.
118
 - Limited layout features, intricate layouts are typically crafted in code.
119
120
121
 CONTROLS GUIDE
122
 ==============
123
124
 - MOUSE CONTROLS
125
   - Mouse wheel:                   Scroll vertically.
126
   - SHIFT+Mouse wheel:             Scroll horizontally.
127
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
128
   - Click ^, Double-Click title:   Collapse window.
129
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
130
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
131
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
132
133
 - TEXT EDITOR
134
   - Hold SHIFT or Drag Mouse:      Select text.
135
   - CTRL+Left/Right:               Word jump.
136
   - CTRL+Shift+Left/Right:         Select words.
137
   - CTRL+A or Double-Click:        Select All.
138
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
139
   - CTRL+Z, CTRL+Y:                Undo, Redo.
140
   - ESCAPE:                        Revert text to its original value.
141
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
142
143
 - KEYBOARD CONTROLS
144
   - Basic:
145
     - Tab, SHIFT+Tab               Cycle through text editable fields.
146
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
147
     - CTRL+Click                   Input text into a Slider or Drag widget.
148
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
149
     - Tab, SHIFT+Tab:              Cycle through every items.
150
     - Arrow keys                   Move through items using directional navigation. Tweak value.
151
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
152
     - Enter                        Activate item (prefer text input when possible).
153
     - Space                        Activate item (prefer tweaking with arrows when possible).
154
     - Escape                       Deactivate item, leave child window, close popup.
155
     - Page Up, Page Down           Previous page, next page.
156
     - Home, End                    Scroll to top, scroll to bottom.
157
     - Alt                          Toggle between scrolling layer and menu layer.
158
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
159
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
160
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
161
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
162
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
163
164
 - GAMEPAD CONTROLS
165
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
166
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
167
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
168
   - Backend support: backend needs to:
169
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
170
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
171
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
172
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
173
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
174
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
175
176
 - REMOTE INPUTS SHARING & MOUSE EMULATION
177
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
178
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
179
     in order to share your PC mouse/keyboard.
180
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
181
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
182
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
183
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
184
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
185
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
186
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
187
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
188
189
190
 PROGRAMMER GUIDE
191
 ================
192
193
 READ FIRST
194
 ----------
195
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
196
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
197
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
198
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
199
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
200
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
201
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
202
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
203
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
204
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
205
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
206
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
207
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
208
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
209
   If you get an assert, read the messages and comments around the assert.
210
 - This codebase aims to be highly optimized:
211
   - A typical idle frame should never call malloc/free.
212
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
213
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
214
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
215
 - This codebase aims to be both highly opinionated and highly flexible:
216
   - This code works because of the things it choose to solve or not solve.
217
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
218
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
219
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
220
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
221
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
222
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
223
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
224
     (so don't use ImVector in your code or at our own risk!).
225
   - Building: We don't use nor mandate a build system for the main library.
226
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
227
     This is also because providing a build system for the main library would be of little-value.
228
     The build problems are almost never coming from the main library but from specific backends.
229
230
231
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
232
 ----------------------------------------------
233
 - Update submodule or copy/overwrite every file.
234
 - About imconfig.h:
235
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
236
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
237
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
238
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
239
240
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
241
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
242
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
243
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
244
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
245
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
246
   likely be a comment about it. Please report any issue to the GitHub page!
247
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
248
 - Try to keep your copy of Dear ImGui reasonably up to date!
249
250
251
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
252
 ---------------------------------------------------------------
253
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
254
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
255
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
256
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
257
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
258
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
259
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
260
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
261
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
262
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
263
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
264
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
265
266
267
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
268
 --------------------------------------
269
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
270
 The sub-folders in examples/ contain examples applications following this structure.
271
272
     // Application init: create a dear imgui context, setup some options, load fonts
273
     ImGui::CreateContext();
274
     ImGuiIO& io = ImGui::GetIO();
275
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
276
     // TODO: Fill optional fields of the io structure later.
277
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
278
279
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
280
     ImGui_ImplWin32_Init(hwnd);
281
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
282
283
     // Application main loop
284
     while (true)
285
     {
286
         // Feed inputs to dear imgui, start new frame
287
         ImGui_ImplDX11_NewFrame();
288
         ImGui_ImplWin32_NewFrame();
289
         ImGui::NewFrame();
290
291
         // Any application code here
292
         ImGui::Text("Hello, world!");
293
294
         // Render dear imgui into screen
295
         ImGui::Render();
296
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
297
         g_pSwapChain->Present(1, 0);
298
     }
299
300
     // Shutdown
301
     ImGui_ImplDX11_Shutdown();
302
     ImGui_ImplWin32_Shutdown();
303
     ImGui::DestroyContext();
304
305
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
306
307
     // Application init: create a dear imgui context, setup some options, load fonts
308
     ImGui::CreateContext();
309
     ImGuiIO& io = ImGui::GetIO();
310
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
311
     // TODO: Fill optional fields of the io structure later.
312
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
313
314
     // Build and load the texture atlas into a texture
315
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
316
     int width, height;
317
     unsigned char* pixels = nullptr;
318
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
319
320
     // At this point you've got the texture data and you need to upload that to your graphic system:
321
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
322
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
323
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
324
     io.Fonts->SetTexID((void*)texture);
325
326
     // Application main loop
327
     while (true)
328
     {
329
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
330
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
331
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
332
        io.DisplaySize.x = 1920.0f;             // set the current display width
333
        io.DisplaySize.y = 1280.0f;             // set the current display height here
334
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
335
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
336
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
337
338
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
339
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
340
        ImGui::NewFrame();
341
342
        // Most of your application code here
343
        ImGui::Text("Hello, world!");
344
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
345
        MyGameRender(); // may use any Dear ImGui functions as well!
346
347
        // Render dear imgui, swap buffers
348
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
349
        ImGui::EndFrame();
350
        ImGui::Render();
351
        ImDrawData* draw_data = ImGui::GetDrawData();
352
        MyImGuiRenderFunction(draw_data);
353
        SwapBuffers();
354
     }
355
356
     // Shutdown
357
     ImGui::DestroyContext();
358
359
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
360
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
361
 Please read the FAQ and example applications for details about this!
362
363
364
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
365
 ---------------------------------------------
366
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
367
368
    void MyImGuiRenderFunction(ImDrawData* draw_data)
369
    {
370
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
371
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
372
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
373
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
374
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
375
       ImVec2 clip_off = draw_data->DisplayPos;
376
       for (int n = 0; n < draw_data->CmdListsCount; n++)
377
       {
378
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
379
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
380
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
381
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
382
          {
383
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
384
             if (pcmd->UserCallback)
385
             {
386
                 pcmd->UserCallback(cmd_list, pcmd);
387
             }
388
             else
389
             {
390
                 // Project scissor/clipping rectangles into framebuffer space
391
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
392
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
393
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
394
                     continue;
395
396
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
397
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
398
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
399
                 // - Clipping coordinates are provided in imgui coordinates space:
400
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
401
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
402
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
403
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
404
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
405
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
406
407
                 // The texture for the draw call is specified by pcmd->GetTexID().
408
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
409
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
410
411
                 // Render 'pcmd->ElemCount/3' indexed triangles.
412
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
413
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
414
             }
415
          }
416
       }
417
    }
418
419
420
 API BREAKING CHANGES
421
 ====================
422
423
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
424
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
425
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
426
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
427
428
(Docking/Viewport Branch)
429
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
430
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
431
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
432
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
433
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
434
435
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
436
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
437
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
438
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
439
                           - old: BeginChild("Name", size, true)
440
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
441
                           - old: BeginChild("Name", size, false)
442
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
443
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
444
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
445
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
446
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
447
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
448
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
449
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
450
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
451
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
452
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
453
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
454
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
455
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
456
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
457
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
458
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
459
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
460
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
461
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
462
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
463
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
464
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
465
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
466
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
467
                           - ListBoxFooter()  -> use EndListBox()
468
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
469
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
470
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
471
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
472
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
473
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
474
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
475
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
476
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
477
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
478
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
479
                         it has been frequently requested by people to use our own. We had an opt-in define which was
480
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
481
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
482
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
483
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
484
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
485
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
486
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
487
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
488
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
489
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
490
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
491
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
492
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
493
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
494
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
495
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
496
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
497
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
498
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
499
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
500
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
501
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
502
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
503
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
504
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
505
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
506
                         - previously this would make the window content size ~200x200:
507
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
508
                         - instead, please submit an item:
509
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
510
                         - alternative:
511
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
512
                         - content size is now only extended when submitting an item!
513
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
514
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
515
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
516
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
517
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
518
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
519
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
520
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
521
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
522
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
523
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
524
                        - Official backends from 1.87+                  -> no issue.
525
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
526
                        - Custom backends not writing to io.NavInputs[] -> no issue.
527
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
528
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
529
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
530
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
531
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
532
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
533
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
534
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
535
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
536
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
537
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
538
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
539
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
540
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
541
                       read https://github.com/ocornut/imgui/issues/4921 for details.
542
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
543
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
544
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
545
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
546
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
547
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
548
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
549
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
550
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
551
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
552
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
553
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
554
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
555
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
556
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
557
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
558
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
559
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
560
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
561
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
562
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
563
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
564
                        - if you are using official backends from the source tree: you have nothing to do.
565
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
566
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
567
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
568
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
569
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
570
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
571
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
572
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
573
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
574
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
575
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
576
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
577
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
578
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
579
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
580
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
581
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
582
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
583
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
584
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
585
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
586
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
587
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
588
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
589
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
590
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
591
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
592
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
593
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
594
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
595
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
596
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
597
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
598
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
599
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
600
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
601
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
602
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
603
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
604
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
605
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
606
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
607
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
608
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
609
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
610
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
611
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
612
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
613
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
614
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
615
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
616
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
617
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
618
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
619
                       - if you omitted the 'power' parameter (likely!), you are not affected.
620
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
621
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
622
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
623
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
624
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
625
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
626
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
627
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
628
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
629
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
630
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
631
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
632
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
633
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
634
                       - ShowTestWindow()                    -> use ShowDemoWindow()
635
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
636
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
637
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
638
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
639
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
640
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
641
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
642
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
643
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
644
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
645
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
646
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
647
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
648
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
649
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
650
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
651
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
652
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
653
                       - ImFont::Glyph                       -> use ImFontGlyph
654
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
655
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
656
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
657
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
658
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
659
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
660
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
661
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
662
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
663
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
664
                       Please reach out if you are affected.
665
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
666
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
667
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
668
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
669
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
670
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
671
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
672
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
673
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
674
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
675
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
676
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
677
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
678
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
679
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
680
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
681
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
682
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
683
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
684
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
685
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
686
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
687
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
688
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
689
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
690
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
691
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
692
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
693
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
694
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
695
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
696
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
697
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
698
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
699
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
700
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
701
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
702
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
703
                       consistent with other functions. Kept redirection functions (will obsolete).
704
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
705
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
706
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
707
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
708
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
709
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
710
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
711
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
712
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
713
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
714
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
715
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
716
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
717
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
718
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
719
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
720
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
721
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
722
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
723
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
724
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
725
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
726
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
727
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
728
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
729
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
730
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
731
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
732
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
733
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
734
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
735
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
736
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
737
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
738
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
739
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
740
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
741
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
742
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
743
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
744
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
745
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
746
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
747
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
748
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
749
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
750
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
751
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
752
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
753
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
754
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
755
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
756
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
757
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
758
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
759
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
760
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
761
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
762
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
763
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
764
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
765
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
766
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
767
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
768
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
769
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
770
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
771
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
772
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
773
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
774
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
775
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
776
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
777
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
778
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
779
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
780
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
781
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
782
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
783
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
784
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
785
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
786
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
787
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
788
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
789
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
790
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
791
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
792
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
793
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
794
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
795
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
796
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
797
                     - the signature of the io.RenderDrawListsFn handler has changed!
798
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
799
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
800
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
801
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
802
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
803
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
804
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
805
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
806
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
807
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
808
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
809
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
810
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
811
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
812
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
813
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
814
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
815
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
816
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
817
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
818
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
819
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
820
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
821
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
822
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
823
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
824
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
825
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
826
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
827
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
828
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
829
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
830
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
831
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
832
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
833
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
834
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
835
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
836
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
837
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
838
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
839
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
840
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
841
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
842
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
843
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
844
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
845
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
846
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
847
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
848
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
849
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
850
851
852
 FREQUENTLY ASKED QUESTIONS (FAQ)
853
 ================================
854
855
 Read all answers online:
856
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
857
 Read all answers locally (with a text editor or ideally a Markdown viewer):
858
   docs/FAQ.md
859
 Some answers are copied down here to facilitate searching in code.
860
861
 Q&A: Basics
862
 ===========
863
864
 Q: Where is the documentation?
865
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
866
    - Run the examples/ applications and explore them.
867
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
868
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
869
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
870
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
871
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
872
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
873
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
874
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
875
    - Your programming IDE is your friend, find the type or function declaration to find comments
876
      associated with it.
877
878
 Q: What is this library called?
879
 Q: Which version should I get?
880
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
881
 >> See https://www.dearimgui.com/faq for details.
882
883
 Q&A: Integration
884
 ================
885
886
 Q: How to get started?
887
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
888
889
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
890
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
891
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
892
893
 Q. How can I enable keyboard or gamepad controls?
894
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
895
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
896
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
897
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
898
 >> See https://www.dearimgui.com/faq
899
900
 Q&A: Usage
901
 ----------
902
903
 Q: About the ID Stack system..
904
   - Why is my widget not reacting when I click on it?
905
   - How can I have widgets with an empty label?
906
   - How can I have multiple widgets with the same label?
907
   - How can I have multiple windows with the same label?
908
 Q: How can I display an image? What is ImTextureID, how does it work?
909
 Q: How can I use my own math types instead of ImVec2?
910
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
911
 Q: How can I display custom shapes? (using low-level ImDrawList API)
912
 >> See https://www.dearimgui.com/faq
913
914
 Q&A: Fonts, Text
915
 ================
916
917
 Q: How should I handle DPI in my application?
918
 Q: How can I load a different font than the default?
919
 Q: How can I easily use icons in my application?
920
 Q: How can I load multiple fonts?
921
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
922
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
923
924
 Q&A: Concerns
925
 =============
926
927
 Q: Who uses Dear ImGui?
928
 Q: Can you create elaborate/serious tools with Dear ImGui?
929
 Q: Can you reskin the look of Dear ImGui?
930
 Q: Why using C++ (as opposed to C)?
931
 >> See https://www.dearimgui.com/faq
932
933
 Q&A: Community
934
 ==============
935
936
 Q: How can I help?
937
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
938
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
939
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
940
      Also see https://github.com/ocornut/imgui/wiki/Sponsors
941
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
942
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
943
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
944
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
945
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
946
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
947
948
*/
949
950
//-------------------------------------------------------------------------
951
// [SECTION] INCLUDES
952
//-------------------------------------------------------------------------
953
954
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
955
#define _CRT_SECURE_NO_WARNINGS
956
#endif
957
958
#ifndef IMGUI_DEFINE_MATH_OPERATORS
959
#define IMGUI_DEFINE_MATH_OPERATORS
960
#endif
961
962
#include "imgui.h"
963
#ifndef IMGUI_DISABLE
964
#include "imgui_internal.h"
965
966
// System includes
967
#include <stdio.h>      // vsnprintf, sscanf, printf
968
#include <stdint.h>     // intptr_t
969
970
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
971
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
972
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
973
#endif
974
975
// [Windows] OS specific includes (optional)
976
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
977
#define IMGUI_DISABLE_WIN32_FUNCTIONS
978
#endif
979
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
980
#ifndef WIN32_LEAN_AND_MEAN
981
#define WIN32_LEAN_AND_MEAN
982
#endif
983
#ifndef NOMINMAX
984
#define NOMINMAX
985
#endif
986
#ifndef __MINGW32__
987
#include <Windows.h>        // _wfopen, OpenClipboard
988
#else
989
#include <windows.h>
990
#endif
991
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
992
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
993
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
994
#endif
995
#endif
996
997
// [Apple] OS specific includes
998
#if defined(__APPLE__)
999
#include <TargetConditionals.h>
1000
#endif
1001
1002
// Visual Studio warnings
1003
#ifdef _MSC_VER
1004
#pragma warning (disable: 4127)             // condition expression is constant
1005
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1006
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1007
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1008
#endif
1009
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1010
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1011
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1012
#endif
1013
1014
// Clang/GCC warnings with -Weverything
1015
#if defined(__clang__)
1016
#if __has_warning("-Wunknown-warning-option")
1017
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1018
#endif
1019
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1020
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1021
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1022
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1023
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1024
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1025
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1026
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1027
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1028
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1029
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1030
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1031
#elif defined(__GNUC__)
1032
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1033
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1034
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1035
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1036
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1037
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1038
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1039
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1040
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1041
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1042
#endif
1043
1044
// Debug options
1045
51.9k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
1046
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1047
1048
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1049
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1050
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1051
1052
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1053
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1054
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1055
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1056
1057
// Tooltip offset
1058
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1059
1060
// Docking
1061
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1062
1063
//-------------------------------------------------------------------------
1064
// [SECTION] FORWARD DECLARATIONS
1065
//-------------------------------------------------------------------------
1066
1067
static void             SetCurrentWindow(ImGuiWindow* window);
1068
static void             FindHoveredWindow();
1069
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1070
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1071
1072
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1073
1074
// Settings
1075
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1076
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1077
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1078
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1079
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1080
1081
// Platform Dependents default implementation for IO functions
1082
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1083
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1084
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1085
1086
namespace ImGui
1087
{
1088
// Navigation
1089
static void             NavUpdate();
1090
static void             NavUpdateWindowing();
1091
static void             NavUpdateWindowingOverlay();
1092
static void             NavUpdateCancelRequest();
1093
static void             NavUpdateCreateMoveRequest();
1094
static void             NavUpdateCreateTabbingRequest();
1095
static float            NavUpdatePageUpPageDown();
1096
static inline void      NavUpdateAnyRequestFlag();
1097
static void             NavUpdateCreateWrappingRequest();
1098
static void             NavEndFrame();
1099
static bool             NavScoreItem(ImGuiNavItemData* result);
1100
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1101
static void             NavProcessItem();
1102
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1103
static ImVec2           NavCalcPreferredRefPos();
1104
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1105
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1106
static void             NavRestoreLayer(ImGuiNavLayer layer);
1107
static int              FindWindowFocusIndex(ImGuiWindow* window);
1108
1109
// Error Checking and Debug Tools
1110
static void             ErrorCheckNewFrameSanityChecks();
1111
static void             ErrorCheckEndFrameSanityChecks();
1112
static void             UpdateDebugToolItemPicker();
1113
static void             UpdateDebugToolStackQueries();
1114
1115
// Inputs
1116
static void             UpdateKeyboardInputs();
1117
static void             UpdateMouseInputs();
1118
static void             UpdateMouseWheel();
1119
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1120
1121
// Misc
1122
static void             UpdateSettings();
1123
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1124
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1125
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1126
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1127
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1128
static void             RenderDimmedBackgrounds();
1129
1130
// Viewports
1131
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1132
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1133
static void             DestroyViewport(ImGuiViewportP* viewport);
1134
static void             UpdateViewportsNewFrame();
1135
static void             UpdateViewportsEndFrame();
1136
static void             WindowSelectViewport(ImGuiWindow* window);
1137
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1138
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1139
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1140
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1141
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1142
static int              FindPlatformMonitorForRect(const ImRect& r);
1143
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1144
1145
}
1146
1147
//-----------------------------------------------------------------------------
1148
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1149
//-----------------------------------------------------------------------------
1150
1151
// DLL users:
1152
// - Heaps and globals are not shared across DLL boundaries!
1153
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1154
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1155
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1156
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1157
1158
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1159
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1160
//   Change to a different context by calling ImGui::SetCurrentContext().
1161
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1162
//   If you want thread-safety to allow N threads to access N different contexts:
1163
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1164
//         struct ImGuiContext;
1165
//         extern thread_local ImGuiContext* MyImGuiTLS;
1166
//         #define GImGui MyImGuiTLS
1167
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1168
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1169
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1170
// - DLL users: read comments above.
1171
#ifndef GImGui
1172
ImGuiContext*   GImGui = NULL;
1173
#endif
1174
1175
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1176
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1177
// - DLL users: read comments above.
1178
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1179
1.23k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1180
1.18k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1181
#else
1182
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1183
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1184
#endif
1185
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1186
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1187
static void*                GImAllocatorUserData = NULL;
1188
1189
//-----------------------------------------------------------------------------
1190
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1191
//-----------------------------------------------------------------------------
1192
1193
ImGuiStyle::ImGuiStyle()
1194
1
{
1195
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1196
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1197
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1198
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1199
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1200
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1201
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1202
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1203
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1204
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1205
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1206
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1207
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1208
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1209
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1210
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1211
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1212
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell. CellPadding.y may be altered between different rows.
1213
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1214
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1215
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1216
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1217
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1218
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1219
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1220
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1221
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1222
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1223
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1224
1
    TabBarBorderSize        = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1225
1
    TableAngledHeadersAngle = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1226
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1227
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1228
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1229
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1230
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1231
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1232
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1233
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1234
1
    DockingSeparatorSize    = 2.0f;             // Thickness of resizing border between docked windows
1235
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1236
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1237
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1238
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1239
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1240
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1241
1242
    // Behaviors
1243
1
    HoverStationaryDelay    = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1244
1
    HoverDelayShort         = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1245
1
    HoverDelayNormal        = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1246
1
    HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1247
1
    HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1248
1249
    // Default theme
1250
1
    ImGui::StyleColorsDark(this);
1251
1
}
1252
1253
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1254
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1255
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1256
0
{
1257
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1258
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1259
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1260
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1261
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1262
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1263
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1264
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1265
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1266
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1267
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1268
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1269
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1270
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1271
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1272
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1273
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1274
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1275
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1276
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1277
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1278
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1279
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1280
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1281
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1282
0
}
1283
1284
ImGuiIO::ImGuiIO()
1285
1
{
1286
    // Most fields are initialized with zero
1287
1
    memset(this, 0, sizeof(*this));
1288
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1289
1290
    // Settings
1291
1
    ConfigFlags = ImGuiConfigFlags_None;
1292
1
    BackendFlags = ImGuiBackendFlags_None;
1293
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1294
1
    DeltaTime = 1.0f / 60.0f;
1295
1
    IniSavingRate = 5.0f;
1296
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1297
1
    LogFilename = "imgui_log.txt";
1298
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1299
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1300
        KeyMap[i] = -1;
1301
#endif
1302
1
    UserData = NULL;
1303
1304
1
    Fonts = NULL;
1305
1
    FontGlobalScale = 1.0f;
1306
1
    FontDefault = NULL;
1307
1
    FontAllowUserScaling = false;
1308
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1309
1310
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1311
1
    ConfigDockingNoSplit = false;
1312
1
    ConfigDockingWithShift = false;
1313
1
    ConfigDockingAlwaysTabBar = false;
1314
1
    ConfigDockingTransparentPayload = false;
1315
1316
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1317
1
    ConfigViewportsNoAutoMerge = false;
1318
1
    ConfigViewportsNoTaskBarIcon = false;
1319
1
    ConfigViewportsNoDecoration = true;
1320
1
    ConfigViewportsNoDefaultParent = false;
1321
1322
    // Miscellaneous options
1323
1
    MouseDrawCursor = false;
1324
#ifdef __APPLE__
1325
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1326
#else
1327
1
    ConfigMacOSXBehaviors = false;
1328
1
#endif
1329
1
    ConfigInputTrickleEventQueue = true;
1330
1
    ConfigInputTextCursorBlink = true;
1331
1
    ConfigInputTextEnterKeepActive = false;
1332
1
    ConfigDragClickToInputText = false;
1333
1
    ConfigWindowsResizeFromEdges = true;
1334
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1335
1
    ConfigMemoryCompactTimer = 60.0f;
1336
1
    ConfigDebugBeginReturnValueOnce = false;
1337
1
    ConfigDebugBeginReturnValueLoop = false;
1338
1339
    // Inputs Behaviors
1340
1
    MouseDoubleClickTime = 0.30f;
1341
1
    MouseDoubleClickMaxDist = 6.0f;
1342
1
    MouseDragThreshold = 6.0f;
1343
1
    KeyRepeatDelay = 0.275f;
1344
1
    KeyRepeatRate = 0.050f;
1345
1346
    // Platform Functions
1347
    // Note: Initialize() will setup default clipboard/ime handlers.
1348
1
    BackendPlatformName = BackendRendererName = NULL;
1349
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1350
1
    PlatformLocaleDecimalPoint = '.';
1351
1352
    // Input (NB: we already have memset zero the entire structure!)
1353
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1354
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1355
1
    MouseSource = ImGuiMouseSource_Mouse;
1356
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1357
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1358
1
    AppAcceptingEvents = true;
1359
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1360
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1361
1
}
1362
1363
// Pass in translated ASCII characters for text input.
1364
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1365
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1366
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1367
void ImGuiIO::AddInputCharacter(unsigned int c)
1368
1.65k
{
1369
1.65k
    IM_ASSERT(Ctx != NULL);
1370
1.65k
    ImGuiContext& g = *Ctx;
1371
1.65k
    if (c == 0 || !AppAcceptingEvents)
1372
561
        return;
1373
1374
1.08k
    ImGuiInputEvent e;
1375
1.08k
    e.Type = ImGuiInputEventType_Text;
1376
1.08k
    e.Source = ImGuiInputSource_Keyboard;
1377
1.08k
    e.EventId = g.InputEventsNextEventId++;
1378
1.08k
    e.Text.Char = c;
1379
1.08k
    g.InputEventsQueue.push_back(e);
1380
1.08k
}
1381
1382
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1383
// we should save the high surrogate.
1384
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1385
600
{
1386
600
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1387
160
        return;
1388
1389
440
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1390
185
    {
1391
185
        if (InputQueueSurrogate != 0)
1392
63
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1393
185
        InputQueueSurrogate = c;
1394
185
        return;
1395
185
    }
1396
1397
255
    ImWchar cp = c;
1398
255
    if (InputQueueSurrogate != 0)
1399
116
    {
1400
116
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1401
40
        {
1402
40
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1403
40
        }
1404
76
        else
1405
76
        {
1406
76
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1407
76
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1408
#else
1409
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1410
#endif
1411
76
        }
1412
1413
116
        InputQueueSurrogate = 0;
1414
116
    }
1415
255
    AddInputCharacter((unsigned)cp);
1416
255
}
1417
1418
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1419
0
{
1420
0
    if (!AppAcceptingEvents)
1421
0
        return;
1422
0
    while (*utf8_chars != 0)
1423
0
    {
1424
0
        unsigned int c = 0;
1425
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1426
0
        AddInputCharacter(c);
1427
0
    }
1428
0
}
1429
1430
// Clear all incoming events.
1431
void ImGuiIO::ClearEventsQueue()
1432
0
{
1433
0
    IM_ASSERT(Ctx != NULL);
1434
0
    ImGuiContext& g = *Ctx;
1435
0
    g.InputEventsQueue.clear();
1436
0
}
1437
1438
// Clear current keyboard/mouse/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1439
void ImGuiIO::ClearInputKeys()
1440
1.12k
{
1441
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1442
    memset(KeysDown, 0, sizeof(KeysDown));
1443
#endif
1444
174k
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1445
173k
    {
1446
173k
        KeysData[n].Down             = false;
1447
173k
        KeysData[n].DownDuration     = -1.0f;
1448
173k
        KeysData[n].DownDurationPrev = -1.0f;
1449
173k
    }
1450
1.12k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1451
1.12k
    KeyMods = ImGuiMod_None;
1452
1.12k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1453
6.76k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1454
5.63k
    {
1455
5.63k
        MouseDown[n] = false;
1456
5.63k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1457
5.63k
    }
1458
1.12k
    MouseWheel = MouseWheelH = 0.0f;
1459
1.12k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1460
1.12k
}
1461
1462
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1463
// Current frame character buffer is now also cleared by ClearInputKeys().
1464
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1465
void ImGuiIO::ClearInputCharacters()
1466
{
1467
    InputQueueCharacters.resize(0);
1468
}
1469
#endif
1470
1471
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1472
4.99k
{
1473
4.99k
    ImGuiContext& g = *ctx;
1474
6.95k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1475
3.98k
    {
1476
3.98k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1477
3.98k
        if (e->Type != type)
1478
1.58k
            continue;
1479
2.40k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1480
308
            continue;
1481
2.09k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1482
69
            continue;
1483
2.02k
        return e;
1484
2.09k
    }
1485
2.96k
    return NULL;
1486
4.99k
}
1487
1488
// Queue a new key down/up event.
1489
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1490
// - bool down:          Is the key down? use false to signify a key release.
1491
// - float analog_value: 0.0f..1.0f
1492
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1493
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1494
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1495
1.01k
{
1496
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1497
1.01k
    IM_ASSERT(Ctx != NULL);
1498
1.01k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1499
0
        return;
1500
1.01k
    ImGuiContext& g = *Ctx;
1501
1.01k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1502
1.01k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1503
1.01k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1504
1505
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1506
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1507
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1508
    if (BackendUsingLegacyKeyArrays == -1)
1509
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1510
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1511
    BackendUsingLegacyKeyArrays = 0;
1512
#endif
1513
1.01k
    if (ImGui::IsGamepadKey(key))
1514
0
        BackendUsingLegacyNavInputArray = false;
1515
1516
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1517
1.01k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1518
1.01k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1519
1.01k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1520
1.01k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1521
1.01k
    if (latest_key_down == down && latest_key_analog == analog_value)
1522
219
        return;
1523
1524
    // Add event
1525
795
    ImGuiInputEvent e;
1526
795
    e.Type = ImGuiInputEventType_Key;
1527
795
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1528
795
    e.EventId = g.InputEventsNextEventId++;
1529
795
    e.Key.Key = key;
1530
795
    e.Key.Down = down;
1531
795
    e.Key.AnalogValue = analog_value;
1532
795
    g.InputEventsQueue.push_back(e);
1533
795
}
1534
1535
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1536
80
{
1537
80
    if (!AppAcceptingEvents)
1538
0
        return;
1539
80
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1540
80
}
1541
1542
// [Optional] Call after AddKeyEvent().
1543
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1544
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1545
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1546
0
{
1547
0
    if (key == ImGuiKey_None)
1548
0
        return;
1549
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1550
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1551
0
    IM_UNUSED(native_keycode);  // Yet unused
1552
0
    IM_UNUSED(native_scancode); // Yet unused
1553
1554
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1555
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1556
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1557
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1558
        return;
1559
    KeyMap[legacy_key] = key;
1560
    KeyMap[key] = legacy_key;
1561
#else
1562
0
    IM_UNUSED(key);
1563
0
    IM_UNUSED(native_legacy_index);
1564
0
#endif
1565
0
}
1566
1567
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1568
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1569
0
{
1570
0
    AppAcceptingEvents = accepting_events;
1571
0
}
1572
1573
// Queue a mouse move event
1574
void ImGuiIO::AddMousePosEvent(float x, float y)
1575
1.75k
{
1576
1.75k
    IM_ASSERT(Ctx != NULL);
1577
1.75k
    ImGuiContext& g = *Ctx;
1578
1.75k
    if (!AppAcceptingEvents)
1579
0
        return;
1580
1581
    // Apply same flooring as UpdateMouseInputs()
1582
1.75k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1583
1584
    // Filter duplicate
1585
1.75k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1586
1.75k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1587
1.75k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1588
120
        return;
1589
1590
1.63k
    ImGuiInputEvent e;
1591
1.63k
    e.Type = ImGuiInputEventType_MousePos;
1592
1.63k
    e.Source = ImGuiInputSource_Mouse;
1593
1.63k
    e.EventId = g.InputEventsNextEventId++;
1594
1.63k
    e.MousePos.PosX = pos.x;
1595
1.63k
    e.MousePos.PosY = pos.y;
1596
1.63k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1597
1.63k
    g.InputEventsQueue.push_back(e);
1598
1.63k
}
1599
1600
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1601
1.88k
{
1602
1.88k
    IM_ASSERT(Ctx != NULL);
1603
1.88k
    ImGuiContext& g = *Ctx;
1604
1.88k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1605
1.88k
    if (!AppAcceptingEvents)
1606
0
        return;
1607
1608
    // Filter duplicate
1609
1.88k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1610
1.88k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1611
1.88k
    if (latest_button_down == down)
1612
122
        return;
1613
1614
1.76k
    ImGuiInputEvent e;
1615
1.76k
    e.Type = ImGuiInputEventType_MouseButton;
1616
1.76k
    e.Source = ImGuiInputSource_Mouse;
1617
1.76k
    e.EventId = g.InputEventsNextEventId++;
1618
1.76k
    e.MouseButton.Button = mouse_button;
1619
1.76k
    e.MouseButton.Down = down;
1620
1.76k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1621
1.76k
    g.InputEventsQueue.push_back(e);
1622
1.76k
}
1623
1624
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1625
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1626
427
{
1627
427
    IM_ASSERT(Ctx != NULL);
1628
427
    ImGuiContext& g = *Ctx;
1629
1630
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1631
427
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1632
5
        return;
1633
1634
422
    ImGuiInputEvent e;
1635
422
    e.Type = ImGuiInputEventType_MouseWheel;
1636
422
    e.Source = ImGuiInputSource_Mouse;
1637
422
    e.EventId = g.InputEventsNextEventId++;
1638
422
    e.MouseWheel.WheelX = wheel_x;
1639
422
    e.MouseWheel.WheelY = wheel_y;
1640
422
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1641
422
    g.InputEventsQueue.push_back(e);
1642
422
}
1643
1644
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1645
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1646
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1647
0
{
1648
0
    IM_ASSERT(Ctx != NULL);
1649
0
    ImGuiContext& g = *Ctx;
1650
0
    g.InputEventsNextMouseSource = source;
1651
0
}
1652
1653
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1654
0
{
1655
0
    IM_ASSERT(Ctx != NULL);
1656
0
    ImGuiContext& g = *Ctx;
1657
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1658
0
    if (!AppAcceptingEvents)
1659
0
        return;
1660
1661
    // Filter duplicate
1662
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1663
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1664
0
    if (latest_viewport_id == viewport_id)
1665
0
        return;
1666
1667
0
    ImGuiInputEvent e;
1668
0
    e.Type = ImGuiInputEventType_MouseViewport;
1669
0
    e.Source = ImGuiInputSource_Mouse;
1670
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1671
0
    g.InputEventsQueue.push_back(e);
1672
0
}
1673
1674
void ImGuiIO::AddFocusEvent(bool focused)
1675
335
{
1676
335
    IM_ASSERT(Ctx != NULL);
1677
335
    ImGuiContext& g = *Ctx;
1678
1679
    // Filter duplicate
1680
335
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1681
335
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1682
335
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1683
21
        return;
1684
1685
314
    ImGuiInputEvent e;
1686
314
    e.Type = ImGuiInputEventType_Focus;
1687
314
    e.EventId = g.InputEventsNextEventId++;
1688
314
    e.AppFocused.Focused = focused;
1689
314
    g.InputEventsQueue.push_back(e);
1690
314
}
1691
1692
//-----------------------------------------------------------------------------
1693
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1694
//-----------------------------------------------------------------------------
1695
1696
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1697
0
{
1698
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1699
0
    ImVec2 p_last = p1;
1700
0
    ImVec2 p_closest;
1701
0
    float p_closest_dist2 = FLT_MAX;
1702
0
    float t_step = 1.0f / (float)num_segments;
1703
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1704
0
    {
1705
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1706
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1707
0
        float dist2 = ImLengthSqr(p - p_line);
1708
0
        if (dist2 < p_closest_dist2)
1709
0
        {
1710
0
            p_closest = p_line;
1711
0
            p_closest_dist2 = dist2;
1712
0
        }
1713
0
        p_last = p_current;
1714
0
    }
1715
0
    return p_closest;
1716
0
}
1717
1718
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1719
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1720
0
{
1721
0
    float dx = x4 - x1;
1722
0
    float dy = y4 - y1;
1723
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1724
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1725
0
    d2 = (d2 >= 0) ? d2 : -d2;
1726
0
    d3 = (d3 >= 0) ? d3 : -d3;
1727
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1728
0
    {
1729
0
        ImVec2 p_current(x4, y4);
1730
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1731
0
        float dist2 = ImLengthSqr(p - p_line);
1732
0
        if (dist2 < p_closest_dist2)
1733
0
        {
1734
0
            p_closest = p_line;
1735
0
            p_closest_dist2 = dist2;
1736
0
        }
1737
0
        p_last = p_current;
1738
0
    }
1739
0
    else if (level < 10)
1740
0
    {
1741
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1742
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1743
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1744
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1745
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1746
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1747
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1748
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1749
0
    }
1750
0
}
1751
1752
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1753
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1754
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1755
0
{
1756
0
    IM_ASSERT(tess_tol > 0.0f);
1757
0
    ImVec2 p_last = p1;
1758
0
    ImVec2 p_closest;
1759
0
    float p_closest_dist2 = FLT_MAX;
1760
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1761
0
    return p_closest;
1762
0
}
1763
1764
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1765
0
{
1766
0
    ImVec2 ap = p - a;
1767
0
    ImVec2 ab_dir = b - a;
1768
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1769
0
    if (dot < 0.0f)
1770
0
        return a;
1771
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1772
0
    if (dot > ab_len_sqr)
1773
0
        return b;
1774
0
    return a + ab_dir * dot / ab_len_sqr;
1775
0
}
1776
1777
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1778
0
{
1779
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1780
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1781
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1782
0
    return ((b1 == b2) && (b2 == b3));
1783
0
}
1784
1785
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1786
0
{
1787
0
    ImVec2 v0 = b - a;
1788
0
    ImVec2 v1 = c - a;
1789
0
    ImVec2 v2 = p - a;
1790
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1791
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1792
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1793
0
    out_u = 1.0f - out_v - out_w;
1794
0
}
1795
1796
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1797
0
{
1798
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1799
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1800
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1801
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1802
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1803
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1804
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1805
0
    if (m == dist2_ab)
1806
0
        return proj_ab;
1807
0
    if (m == dist2_bc)
1808
0
        return proj_bc;
1809
0
    return proj_ca;
1810
0
}
1811
1812
//-----------------------------------------------------------------------------
1813
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1814
//-----------------------------------------------------------------------------
1815
1816
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1817
int ImStricmp(const char* str1, const char* str2)
1818
0
{
1819
0
    int d;
1820
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1821
0
    return d;
1822
0
}
1823
1824
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1825
0
{
1826
0
    int d = 0;
1827
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1828
0
    return d;
1829
0
}
1830
1831
void ImStrncpy(char* dst, const char* src, size_t count)
1832
0
{
1833
0
    if (count < 1)
1834
0
        return;
1835
0
    if (count > 1)
1836
0
        strncpy(dst, src, count - 1);
1837
0
    dst[count - 1] = 0;
1838
0
}
1839
1840
char* ImStrdup(const char* str)
1841
3
{
1842
3
    size_t len = strlen(str);
1843
3
    void* buf = IM_ALLOC(len + 1);
1844
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1845
3
}
1846
1847
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1848
0
{
1849
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1850
0
    size_t src_size = strlen(src) + 1;
1851
0
    if (dst_buf_size < src_size)
1852
0
    {
1853
0
        IM_FREE(dst);
1854
0
        dst = (char*)IM_ALLOC(src_size);
1855
0
        if (p_dst_size)
1856
0
            *p_dst_size = src_size;
1857
0
    }
1858
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1859
0
}
1860
1861
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1862
0
{
1863
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1864
0
    return p;
1865
0
}
1866
1867
int ImStrlenW(const ImWchar* str)
1868
0
{
1869
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1870
0
    int n = 0;
1871
0
    while (*str++) n++;
1872
0
    return n;
1873
0
}
1874
1875
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1876
const char* ImStreolRange(const char* str, const char* str_end)
1877
0
{
1878
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1879
0
    return p ? p : str_end;
1880
0
}
1881
1882
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1883
0
{
1884
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1885
0
        buf_mid_line--;
1886
0
    return buf_mid_line;
1887
0
}
1888
1889
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1890
0
{
1891
0
    if (!needle_end)
1892
0
        needle_end = needle + strlen(needle);
1893
1894
0
    const char un0 = (char)ImToUpper(*needle);
1895
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1896
0
    {
1897
0
        if (ImToUpper(*haystack) == un0)
1898
0
        {
1899
0
            const char* b = needle + 1;
1900
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1901
0
                if (ImToUpper(*a) != ImToUpper(*b))
1902
0
                    break;
1903
0
            if (b == needle_end)
1904
0
                return haystack;
1905
0
        }
1906
0
        haystack++;
1907
0
    }
1908
0
    return NULL;
1909
0
}
1910
1911
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1912
void ImStrTrimBlanks(char* buf)
1913
0
{
1914
0
    char* p = buf;
1915
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1916
0
        p++;
1917
0
    char* p_start = p;
1918
0
    while (*p != 0)                         // Find end of string
1919
0
        p++;
1920
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1921
0
        p--;
1922
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1923
0
        memmove(buf, p_start, p - p_start);
1924
0
    buf[p - p_start] = 0;                   // Zero terminate
1925
0
}
1926
1927
const char* ImStrSkipBlank(const char* str)
1928
0
{
1929
0
    while (str[0] == ' ' || str[0] == '\t')
1930
0
        str++;
1931
0
    return str;
1932
0
}
1933
1934
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1935
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1936
// B) When buf==NULL vsnprintf() will return the output size.
1937
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1938
1939
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1940
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1941
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1942
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1943
#ifdef IMGUI_USE_STB_SPRINTF
1944
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
1945
#define STB_SPRINTF_IMPLEMENTATION
1946
#endif
1947
#ifdef IMGUI_STB_SPRINTF_FILENAME
1948
#include IMGUI_STB_SPRINTF_FILENAME
1949
#else
1950
#include "stb_sprintf.h"
1951
#endif
1952
#endif // #ifdef IMGUI_USE_STB_SPRINTF
1953
1954
#if defined(_MSC_VER) && !defined(vsnprintf)
1955
#define vsnprintf _vsnprintf
1956
#endif
1957
1958
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1959
1
{
1960
1
    va_list args;
1961
1
    va_start(args, fmt);
1962
#ifdef IMGUI_USE_STB_SPRINTF
1963
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1964
#else
1965
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1966
1
#endif
1967
1
    va_end(args);
1968
1
    if (buf == NULL)
1969
0
        return w;
1970
1
    if (w == -1 || w >= (int)buf_size)
1971
0
        w = (int)buf_size - 1;
1972
1
    buf[w] = 0;
1973
1
    return w;
1974
1
}
1975
1976
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1977
25.7k
{
1978
#ifdef IMGUI_USE_STB_SPRINTF
1979
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1980
#else
1981
25.7k
    int w = vsnprintf(buf, buf_size, fmt, args);
1982
25.7k
#endif
1983
25.7k
    if (buf == NULL)
1984
0
        return w;
1985
25.7k
    if (w == -1 || w >= (int)buf_size)
1986
0
        w = (int)buf_size - 1;
1987
25.7k
    buf[w] = 0;
1988
25.7k
    return w;
1989
25.7k
}
1990
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1991
1992
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1993
25.7k
{
1994
25.7k
    va_list args;
1995
25.7k
    va_start(args, fmt);
1996
25.7k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
1997
25.7k
    va_end(args);
1998
25.7k
}
1999
2000
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2001
25.7k
{
2002
25.7k
    ImGuiContext& g = *GImGui;
2003
25.7k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2004
0
    {
2005
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2006
0
        *out_buf = buf;
2007
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2008
0
    }
2009
25.7k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2010
0
    {
2011
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2012
0
        const char* buf = va_arg(args, const char*);
2013
0
        *out_buf = buf;
2014
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2015
0
    }
2016
25.7k
    else
2017
25.7k
    {
2018
25.7k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2019
25.7k
        *out_buf = g.TempBuffer.Data;
2020
25.7k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2021
25.7k
    }
2022
25.7k
}
2023
2024
// CRC32 needs a 1KB lookup table (not cache friendly)
2025
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2026
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2027
static const ImU32 GCrc32LookupTable[256] =
2028
{
2029
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2030
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2031
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2032
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2033
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2034
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2035
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2036
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2037
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2038
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2039
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2040
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2041
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2042
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2043
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2044
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2045
};
2046
2047
// Known size hash
2048
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2049
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2050
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2051
25.7k
{
2052
25.7k
    ImU32 crc = ~seed;
2053
25.7k
    const unsigned char* data = (const unsigned char*)data_p;
2054
25.7k
    const ImU32* crc32_lut = GCrc32LookupTable;
2055
128k
    while (data_size-- != 0)
2056
103k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2057
25.7k
    return ~crc;
2058
25.7k
}
2059
2060
// Zero-terminated string hash, with support for ### to reset back to seed value
2061
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2062
// Because this syntax is rarely used we are optimizing for the common case.
2063
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2064
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2065
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2066
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2067
284k
{
2068
284k
    seed = ~seed;
2069
284k
    ImU32 crc = seed;
2070
284k
    const unsigned char* data = (const unsigned char*)data_p;
2071
284k
    const ImU32* crc32_lut = GCrc32LookupTable;
2072
284k
    if (data_size != 0)
2073
0
    {
2074
0
        while (data_size-- != 0)
2075
0
        {
2076
0
            unsigned char c = *data++;
2077
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2078
0
                crc = seed;
2079
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2080
0
        }
2081
0
    }
2082
284k
    else
2083
284k
    {
2084
3.58M
        while (unsigned char c = *data++)
2085
3.30M
        {
2086
3.30M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2087
25.7k
                crc = seed;
2088
3.30M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2089
3.30M
        }
2090
284k
    }
2091
284k
    return ~crc;
2092
284k
}
2093
2094
//-----------------------------------------------------------------------------
2095
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2096
//-----------------------------------------------------------------------------
2097
2098
// Default file functions
2099
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2100
2101
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2102
0
{
2103
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2104
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2105
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2106
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2107
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2108
    ImGuiContext& g = *GImGui;
2109
    g.TempBuffer.reserve((filename_wsize + mode_wsize) * sizeof(wchar_t));
2110
    wchar_t* buf = (wchar_t*)(void*)g.TempBuffer.Data;
2111
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2112
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2113
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2114
#else
2115
0
    return fopen(filename, mode);
2116
0
#endif
2117
0
}
2118
2119
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2120
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2121
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2122
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2123
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2124
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2125
2126
// Helper: Load file content into memory
2127
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2128
// This can't really be used with "rt" because fseek size won't match read size.
2129
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2130
0
{
2131
0
    IM_ASSERT(filename && mode);
2132
0
    if (out_file_size)
2133
0
        *out_file_size = 0;
2134
2135
0
    ImFileHandle f;
2136
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2137
0
        return NULL;
2138
2139
0
    size_t file_size = (size_t)ImFileGetSize(f);
2140
0
    if (file_size == (size_t)-1)
2141
0
    {
2142
0
        ImFileClose(f);
2143
0
        return NULL;
2144
0
    }
2145
2146
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2147
0
    if (file_data == NULL)
2148
0
    {
2149
0
        ImFileClose(f);
2150
0
        return NULL;
2151
0
    }
2152
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2153
0
    {
2154
0
        ImFileClose(f);
2155
0
        IM_FREE(file_data);
2156
0
        return NULL;
2157
0
    }
2158
0
    if (padding_bytes > 0)
2159
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2160
2161
0
    ImFileClose(f);
2162
0
    if (out_file_size)
2163
0
        *out_file_size = file_size;
2164
2165
0
    return file_data;
2166
0
}
2167
2168
//-----------------------------------------------------------------------------
2169
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2170
//-----------------------------------------------------------------------------
2171
2172
IM_MSVC_RUNTIME_CHECKS_OFF
2173
2174
// Convert UTF-8 to 32-bit character, process single character input.
2175
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2176
// We handle UTF-8 decoding error by skipping forward.
2177
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2178
2.98M
{
2179
2.98M
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2180
2.98M
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2181
2.98M
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2182
2.98M
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2183
2.98M
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2184
2.98M
    int len = lengths[*(const unsigned char*)in_text >> 3];
2185
2.98M
    int wanted = len + (len ? 0 : 1);
2186
2187
2.98M
    if (in_text_end == NULL)
2188
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2189
2190
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2191
    // so it is fast even with excessive branching.
2192
2.98M
    unsigned char s[4];
2193
2.98M
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2194
2.98M
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2195
2.98M
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2196
2.98M
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2197
2198
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2199
2.98M
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2200
2.98M
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2201
2.98M
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2202
2.98M
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2203
2.98M
    *out_char >>= shiftc[len];
2204
2205
    // Accumulate the various error conditions.
2206
2.98M
    int e = 0;
2207
2.98M
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2208
2.98M
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2209
2.98M
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2210
2.98M
    e |= (s[1] & 0xc0) >> 2;
2211
2.98M
    e |= (s[2] & 0xc0) >> 4;
2212
2.98M
    e |= (s[3]       ) >> 6;
2213
2.98M
    e ^= 0x2a; // top two bits of each tail byte correct?
2214
2.98M
    e >>= shifte[len];
2215
2216
2.98M
    if (e)
2217
225k
    {
2218
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2219
        // One byte is consumed in case of invalid first byte of in_text.
2220
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2221
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2222
225k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2223
225k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2224
225k
    }
2225
2226
2.98M
    return wanted;
2227
2.98M
}
2228
2229
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2230
0
{
2231
0
    ImWchar* buf_out = buf;
2232
0
    ImWchar* buf_end = buf + buf_size;
2233
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2234
0
    {
2235
0
        unsigned int c;
2236
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2237
0
        *buf_out++ = (ImWchar)c;
2238
0
    }
2239
0
    *buf_out = 0;
2240
0
    if (in_text_remaining)
2241
0
        *in_text_remaining = in_text;
2242
0
    return (int)(buf_out - buf);
2243
0
}
2244
2245
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2246
0
{
2247
0
    int char_count = 0;
2248
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2249
0
    {
2250
0
        unsigned int c;
2251
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2252
0
        char_count++;
2253
0
    }
2254
0
    return char_count;
2255
0
}
2256
2257
// Based on stb_to_utf8() from github.com/nothings/stb/
2258
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2259
0
{
2260
0
    if (c < 0x80)
2261
0
    {
2262
0
        buf[0] = (char)c;
2263
0
        return 1;
2264
0
    }
2265
0
    if (c < 0x800)
2266
0
    {
2267
0
        if (buf_size < 2) return 0;
2268
0
        buf[0] = (char)(0xc0 + (c >> 6));
2269
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2270
0
        return 2;
2271
0
    }
2272
0
    if (c < 0x10000)
2273
0
    {
2274
0
        if (buf_size < 3) return 0;
2275
0
        buf[0] = (char)(0xe0 + (c >> 12));
2276
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2277
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2278
0
        return 3;
2279
0
    }
2280
0
    if (c <= 0x10FFFF)
2281
0
    {
2282
0
        if (buf_size < 4) return 0;
2283
0
        buf[0] = (char)(0xf0 + (c >> 18));
2284
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2285
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2286
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2287
0
        return 4;
2288
0
    }
2289
    // Invalid code point, the max unicode is 0x10FFFF
2290
0
    return 0;
2291
0
}
2292
2293
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2294
0
{
2295
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2296
0
    out_buf[count] = 0;
2297
0
    return out_buf;
2298
0
}
2299
2300
// Not optimal but we very rarely use this function.
2301
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2302
0
{
2303
0
    unsigned int unused = 0;
2304
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2305
0
}
2306
2307
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2308
0
{
2309
0
    if (c < 0x80) return 1;
2310
0
    if (c < 0x800) return 2;
2311
0
    if (c < 0x10000) return 3;
2312
0
    if (c <= 0x10FFFF) return 4;
2313
0
    return 3;
2314
0
}
2315
2316
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2317
0
{
2318
0
    char* buf_p = out_buf;
2319
0
    const char* buf_end = out_buf + out_buf_size;
2320
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2321
0
    {
2322
0
        unsigned int c = (unsigned int)(*in_text++);
2323
0
        if (c < 0x80)
2324
0
            *buf_p++ = (char)c;
2325
0
        else
2326
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2327
0
    }
2328
0
    *buf_p = 0;
2329
0
    return (int)(buf_p - out_buf);
2330
0
}
2331
2332
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2333
0
{
2334
0
    int bytes_count = 0;
2335
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2336
0
    {
2337
0
        unsigned int c = (unsigned int)(*in_text++);
2338
0
        if (c < 0x80)
2339
0
            bytes_count++;
2340
0
        else
2341
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2342
0
    }
2343
0
    return bytes_count;
2344
0
}
2345
2346
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2347
0
{
2348
0
    while (in_text_curr > in_text_start)
2349
0
    {
2350
0
        in_text_curr--;
2351
0
        if ((*in_text_curr & 0xC0) != 0x80)
2352
0
            return in_text_curr;
2353
0
    }
2354
0
    return in_text_start;
2355
0
}
2356
2357
IM_MSVC_RUNTIME_CHECKS_RESTORE
2358
2359
//-----------------------------------------------------------------------------
2360
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2361
// Note: The Convert functions are early design which are not consistent with other API.
2362
//-----------------------------------------------------------------------------
2363
2364
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2365
0
{
2366
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2367
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2368
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2369
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2370
0
    return IM_COL32(r, g, b, 0xFF);
2371
0
}
2372
2373
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2374
37.4k
{
2375
37.4k
    float s = 1.0f / 255.0f;
2376
37.4k
    return ImVec4(
2377
37.4k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2378
37.4k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2379
37.4k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2380
37.4k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2381
37.4k
}
2382
2383
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2384
412k
{
2385
412k
    ImU32 out;
2386
412k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2387
412k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2388
412k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2389
412k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2390
412k
    return out;
2391
412k
}
2392
2393
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2394
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2395
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2396
0
{
2397
0
    float K = 0.f;
2398
0
    if (g < b)
2399
0
    {
2400
0
        ImSwap(g, b);
2401
0
        K = -1.f;
2402
0
    }
2403
0
    if (r < g)
2404
0
    {
2405
0
        ImSwap(r, g);
2406
0
        K = -2.f / 6.f - K;
2407
0
    }
2408
2409
0
    const float chroma = r - (g < b ? g : b);
2410
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2411
0
    out_s = chroma / (r + 1e-20f);
2412
0
    out_v = r;
2413
0
}
2414
2415
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2416
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2417
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2418
0
{
2419
0
    if (s == 0.0f)
2420
0
    {
2421
        // gray
2422
0
        out_r = out_g = out_b = v;
2423
0
        return;
2424
0
    }
2425
2426
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2427
0
    int   i = (int)h;
2428
0
    float f = h - (float)i;
2429
0
    float p = v * (1.0f - s);
2430
0
    float q = v * (1.0f - s * f);
2431
0
    float t = v * (1.0f - s * (1.0f - f));
2432
2433
0
    switch (i)
2434
0
    {
2435
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2436
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2437
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2438
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2439
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2440
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2441
0
    }
2442
0
}
2443
2444
//-----------------------------------------------------------------------------
2445
// [SECTION] ImGuiStorage
2446
// Helper: Key->value storage
2447
//-----------------------------------------------------------------------------
2448
2449
// std::lower_bound but without the bullshit
2450
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2451
77.3k
{
2452
77.3k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2453
77.3k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2454
77.3k
    size_t count = (size_t)(last - first);
2455
231k
    while (count > 0)
2456
154k
    {
2457
154k
        size_t count2 = count >> 1;
2458
154k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2459
154k
        if (mid->key < key)
2460
51.5k
        {
2461
51.5k
            first = ++mid;
2462
51.5k
            count -= count2 + 1;
2463
51.5k
        }
2464
103k
        else
2465
103k
        {
2466
103k
            count = count2;
2467
103k
        }
2468
154k
    }
2469
77.3k
    return first;
2470
77.3k
}
2471
2472
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2473
void ImGuiStorage::BuildSortByKey()
2474
0
{
2475
0
    struct StaticFunc
2476
0
    {
2477
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2478
0
        {
2479
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2480
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2481
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2482
0
            return 0;
2483
0
        }
2484
0
    };
2485
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2486
0
}
2487
2488
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2489
0
{
2490
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2491
0
    if (it == Data.end() || it->key != key)
2492
0
        return default_val;
2493
0
    return it->val_i;
2494
0
}
2495
2496
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2497
0
{
2498
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2499
0
}
2500
2501
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2502
0
{
2503
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2504
0
    if (it == Data.end() || it->key != key)
2505
0
        return default_val;
2506
0
    return it->val_f;
2507
0
}
2508
2509
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2510
77.3k
{
2511
77.3k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2512
77.3k
    if (it == Data.end() || it->key != key)
2513
3
        return NULL;
2514
77.3k
    return it->val_p;
2515
77.3k
}
2516
2517
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2518
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2519
0
{
2520
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2521
0
    if (it == Data.end() || it->key != key)
2522
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2523
0
    return &it->val_i;
2524
0
}
2525
2526
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2527
0
{
2528
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2529
0
}
2530
2531
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2532
0
{
2533
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2534
0
    if (it == Data.end() || it->key != key)
2535
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2536
0
    return &it->val_f;
2537
0
}
2538
2539
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2540
0
{
2541
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2542
0
    if (it == Data.end() || it->key != key)
2543
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2544
0
    return &it->val_p;
2545
0
}
2546
2547
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2548
void ImGuiStorage::SetInt(ImGuiID key, int val)
2549
0
{
2550
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2551
0
    if (it == Data.end() || it->key != key)
2552
0
        Data.insert(it, ImGuiStoragePair(key, val));
2553
0
    else
2554
0
        it->val_i = val;
2555
0
}
2556
2557
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2558
0
{
2559
0
    SetInt(key, val ? 1 : 0);
2560
0
}
2561
2562
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2563
0
{
2564
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2565
0
    if (it == Data.end() || it->key != key)
2566
0
        Data.insert(it, ImGuiStoragePair(key, val));
2567
0
    else
2568
0
        it->val_f = val;
2569
0
}
2570
2571
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2572
3
{
2573
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2574
3
    if (it == Data.end() || it->key != key)
2575
3
        Data.insert(it, ImGuiStoragePair(key, val));
2576
0
    else
2577
0
        it->val_p = val;
2578
3
}
2579
2580
void ImGuiStorage::SetAllInt(int v)
2581
0
{
2582
0
    for (int i = 0; i < Data.Size; i++)
2583
0
        Data[i].val_i = v;
2584
0
}
2585
2586
//-----------------------------------------------------------------------------
2587
// [SECTION] ImGuiTextFilter
2588
//-----------------------------------------------------------------------------
2589
2590
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2591
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2592
0
{
2593
0
    InputBuf[0] = 0;
2594
0
    CountGrep = 0;
2595
0
    if (default_filter)
2596
0
    {
2597
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2598
0
        Build();
2599
0
    }
2600
0
}
2601
2602
bool ImGuiTextFilter::Draw(const char* label, float width)
2603
0
{
2604
0
    if (width != 0.0f)
2605
0
        ImGui::SetNextItemWidth(width);
2606
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2607
0
    if (value_changed)
2608
0
        Build();
2609
0
    return value_changed;
2610
0
}
2611
2612
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2613
0
{
2614
0
    out->resize(0);
2615
0
    const char* wb = b;
2616
0
    const char* we = wb;
2617
0
    while (we < e)
2618
0
    {
2619
0
        if (*we == separator)
2620
0
        {
2621
0
            out->push_back(ImGuiTextRange(wb, we));
2622
0
            wb = we + 1;
2623
0
        }
2624
0
        we++;
2625
0
    }
2626
0
    if (wb != we)
2627
0
        out->push_back(ImGuiTextRange(wb, we));
2628
0
}
2629
2630
void ImGuiTextFilter::Build()
2631
0
{
2632
0
    Filters.resize(0);
2633
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2634
0
    input_range.split(',', &Filters);
2635
2636
0
    CountGrep = 0;
2637
0
    for (ImGuiTextRange& f : Filters)
2638
0
    {
2639
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2640
0
            f.b++;
2641
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2642
0
            f.e--;
2643
0
        if (f.empty())
2644
0
            continue;
2645
0
        if (f.b[0] != '-')
2646
0
            CountGrep += 1;
2647
0
    }
2648
0
}
2649
2650
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2651
0
{
2652
0
    if (Filters.empty())
2653
0
        return true;
2654
2655
0
    if (text == NULL)
2656
0
        text = "";
2657
2658
0
    for (const ImGuiTextRange& f : Filters)
2659
0
    {
2660
0
        if (f.empty())
2661
0
            continue;
2662
0
        if (f.b[0] == '-')
2663
0
        {
2664
            // Subtract
2665
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2666
0
                return false;
2667
0
        }
2668
0
        else
2669
0
        {
2670
            // Grep
2671
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2672
0
                return true;
2673
0
        }
2674
0
    }
2675
2676
    // Implicit * grep
2677
0
    if (CountGrep == 0)
2678
0
        return true;
2679
2680
0
    return false;
2681
0
}
2682
2683
//-----------------------------------------------------------------------------
2684
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2685
//-----------------------------------------------------------------------------
2686
2687
// On some platform vsnprintf() takes va_list by reference and modifies it.
2688
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2689
#ifndef va_copy
2690
#if defined(__GNUC__) || defined(__clang__)
2691
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2692
#else
2693
#define va_copy(dest, src) (dest = src)
2694
#endif
2695
#endif
2696
2697
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2698
2699
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2700
0
{
2701
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2702
2703
    // Add zero-terminator the first time
2704
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2705
0
    const int needed_sz = write_off + len;
2706
0
    if (write_off + len >= Buf.Capacity)
2707
0
    {
2708
0
        int new_capacity = Buf.Capacity * 2;
2709
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2710
0
    }
2711
2712
0
    Buf.resize(needed_sz);
2713
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2714
0
    Buf[write_off - 1 + len] = 0;
2715
0
}
2716
2717
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2718
0
{
2719
0
    va_list args;
2720
0
    va_start(args, fmt);
2721
0
    appendfv(fmt, args);
2722
0
    va_end(args);
2723
0
}
2724
2725
// Helper: Text buffer for logging/accumulating text
2726
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2727
0
{
2728
0
    va_list args_copy;
2729
0
    va_copy(args_copy, args);
2730
2731
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2732
0
    if (len <= 0)
2733
0
    {
2734
0
        va_end(args_copy);
2735
0
        return;
2736
0
    }
2737
2738
    // Add zero-terminator the first time
2739
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2740
0
    const int needed_sz = write_off + len;
2741
0
    if (write_off + len >= Buf.Capacity)
2742
0
    {
2743
0
        int new_capacity = Buf.Capacity * 2;
2744
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2745
0
    }
2746
2747
0
    Buf.resize(needed_sz);
2748
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2749
0
    va_end(args_copy);
2750
0
}
2751
2752
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2753
0
{
2754
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2755
0
    if (old_size == new_size)
2756
0
        return;
2757
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2758
0
        LineOffsets.push_back(EndOffset);
2759
0
    const char* base_end = base + new_size;
2760
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2761
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2762
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2763
0
    EndOffset = ImMax(EndOffset, new_size);
2764
0
}
2765
2766
//-----------------------------------------------------------------------------
2767
// [SECTION] ImGuiListClipper
2768
//-----------------------------------------------------------------------------
2769
2770
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2771
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2772
static bool GetSkipItemForListClipping()
2773
0
{
2774
0
    ImGuiContext& g = *GImGui;
2775
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2776
0
}
2777
2778
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2779
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2780
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2781
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2782
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2783
{
2784
    ImGuiContext& g = *GImGui;
2785
    ImGuiWindow* window = g.CurrentWindow;
2786
    if (g.LogEnabled)
2787
    {
2788
        // If logging is active, do not perform any clipping
2789
        *out_items_display_start = 0;
2790
        *out_items_display_end = items_count;
2791
        return;
2792
    }
2793
    if (GetSkipItemForListClipping())
2794
    {
2795
        *out_items_display_start = *out_items_display_end = 0;
2796
        return;
2797
    }
2798
2799
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2800
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2801
    ImRect rect = window->ClipRect;
2802
    if (g.NavMoveScoringItems)
2803
        rect.Add(g.NavScoringNoClipRect);
2804
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2805
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2806
2807
    const ImVec2 pos = window->DC.CursorPos;
2808
    int start = (int)((rect.Min.y - pos.y) / items_height);
2809
    int end = (int)((rect.Max.y - pos.y) / items_height);
2810
2811
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2812
    // FIXME: Verify this works with tabbing
2813
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2814
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2815
        start--;
2816
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2817
        end++;
2818
2819
    start = ImClamp(start, 0, items_count);
2820
    end = ImClamp(end + 1, start, items_count);
2821
    *out_items_display_start = start;
2822
    *out_items_display_end = end;
2823
}
2824
#endif
2825
2826
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2827
0
{
2828
0
    if (ranges.Size - offset <= 1)
2829
0
        return;
2830
2831
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2832
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2833
0
        for (int i = offset; i < sort_end + offset; ++i)
2834
0
            if (ranges[i].Min > ranges[i + 1].Min)
2835
0
                ImSwap(ranges[i], ranges[i + 1]);
2836
2837
    // Now fuse ranges together as much as possible.
2838
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2839
0
    {
2840
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2841
0
        if (ranges[i - 1].Max < ranges[i].Min)
2842
0
            continue;
2843
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2844
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2845
0
        ranges.erase(ranges.Data + i);
2846
0
        i--;
2847
0
    }
2848
0
}
2849
2850
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2851
0
{
2852
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2853
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2854
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2855
0
    ImGuiContext& g = *GImGui;
2856
0
    ImGuiWindow* window = g.CurrentWindow;
2857
0
    float off_y = pos_y - window->DC.CursorPos.y;
2858
0
    window->DC.CursorPos.y = pos_y;
2859
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2860
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2861
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2862
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2863
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2864
0
    if (ImGuiTable* table = g.CurrentTable)
2865
0
    {
2866
0
        if (table->IsInsideRow)
2867
0
            ImGui::TableEndRow(table);
2868
0
        table->RowPosY2 = window->DC.CursorPos.y;
2869
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2870
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2871
0
        table->RowBgColorCounter += row_increase;
2872
0
    }
2873
0
}
2874
2875
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2876
0
{
2877
    // StartPosY starts from ItemsFrozen hence the subtraction
2878
    // Perform the add and multiply with double to allow seeking through larger ranges
2879
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2880
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2881
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2882
0
}
2883
2884
ImGuiListClipper::ImGuiListClipper()
2885
0
{
2886
0
    memset(this, 0, sizeof(*this));
2887
0
}
2888
2889
ImGuiListClipper::~ImGuiListClipper()
2890
0
{
2891
0
    End();
2892
0
}
2893
2894
void ImGuiListClipper::Begin(int items_count, float items_height)
2895
0
{
2896
0
    if (Ctx == NULL)
2897
0
        Ctx = ImGui::GetCurrentContext();
2898
2899
0
    ImGuiContext& g = *Ctx;
2900
0
    ImGuiWindow* window = g.CurrentWindow;
2901
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2902
2903
0
    if (ImGuiTable* table = g.CurrentTable)
2904
0
        if (table->IsInsideRow)
2905
0
            ImGui::TableEndRow(table);
2906
2907
0
    StartPosY = window->DC.CursorPos.y;
2908
0
    ItemsHeight = items_height;
2909
0
    ItemsCount = items_count;
2910
0
    DisplayStart = -1;
2911
0
    DisplayEnd = 0;
2912
2913
    // Acquire temporary buffer
2914
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2915
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2916
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2917
0
    data->Reset(this);
2918
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2919
0
    TempData = data;
2920
0
}
2921
2922
void ImGuiListClipper::End()
2923
0
{
2924
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2925
0
    {
2926
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2927
0
        ImGuiContext& g = *Ctx;
2928
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2929
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2930
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2931
2932
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2933
0
        IM_ASSERT(data->ListClipper == this);
2934
0
        data->StepNo = data->Ranges.Size;
2935
0
        if (--g.ClipperTempDataStacked > 0)
2936
0
        {
2937
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2938
0
            data->ListClipper->TempData = data;
2939
0
        }
2940
0
        TempData = NULL;
2941
0
    }
2942
0
    ItemsCount = -1;
2943
0
}
2944
2945
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
2946
0
{
2947
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2948
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2949
0
    IM_ASSERT(item_begin <= item_end);
2950
0
    if (item_begin < item_end)
2951
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2952
0
}
2953
2954
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2955
0
{
2956
0
    ImGuiContext& g = *clipper->Ctx;
2957
0
    ImGuiWindow* window = g.CurrentWindow;
2958
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2959
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2960
2961
0
    ImGuiTable* table = g.CurrentTable;
2962
0
    if (table && table->IsInsideRow)
2963
0
        ImGui::TableEndRow(table);
2964
2965
    // No items
2966
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2967
0
        return false;
2968
2969
    // While we are in frozen row state, keep displaying items one by one, unclipped
2970
    // FIXME: Could be stored as a table-agnostic state.
2971
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2972
0
    {
2973
0
        clipper->DisplayStart = data->ItemsFrozen;
2974
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2975
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2976
0
            data->ItemsFrozen++;
2977
0
        return true;
2978
0
    }
2979
2980
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2981
0
    bool calc_clipping = false;
2982
0
    if (data->StepNo == 0)
2983
0
    {
2984
0
        clipper->StartPosY = window->DC.CursorPos.y;
2985
0
        if (clipper->ItemsHeight <= 0.0f)
2986
0
        {
2987
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2988
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2989
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2990
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2991
0
            data->StepNo = 1;
2992
0
            return true;
2993
0
        }
2994
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2995
0
    }
2996
2997
    // Step 1: Let the clipper infer height from first range
2998
0
    if (clipper->ItemsHeight <= 0.0f)
2999
0
    {
3000
0
        IM_ASSERT(data->StepNo == 1);
3001
0
        if (table)
3002
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3003
3004
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3005
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3006
0
        if (affected_by_floating_point_precision)
3007
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3008
3009
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3010
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3011
0
    }
3012
3013
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3014
0
    const int already_submitted = clipper->DisplayEnd;
3015
0
    if (calc_clipping)
3016
0
    {
3017
0
        if (g.LogEnabled)
3018
0
        {
3019
            // If logging is active, do not perform any clipping
3020
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3021
0
        }
3022
0
        else
3023
0
        {
3024
            // Add range selected to be included for navigation
3025
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3026
0
            if (is_nav_request)
3027
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3028
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3029
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3030
3031
            // Add focused/active item
3032
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3033
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3034
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3035
3036
            // Add visible range
3037
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3038
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3039
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
3040
0
        }
3041
3042
        // Convert position ranges to item index ranges
3043
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3044
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3045
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3046
0
        for (ImGuiListClipperRange& range : data->Ranges)
3047
0
            if (range.PosToIndexConvert)
3048
0
            {
3049
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3050
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3051
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3052
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3053
0
                range.PosToIndexConvert = false;
3054
0
            }
3055
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3056
0
    }
3057
3058
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3059
0
    while (data->StepNo < data->Ranges.Size)
3060
0
    {
3061
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3062
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3063
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3064
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3065
0
        data->StepNo++;
3066
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3067
0
            continue;
3068
0
        return true;
3069
0
    }
3070
3071
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3072
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3073
0
    if (clipper->ItemsCount < INT_MAX)
3074
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3075
3076
0
    return false;
3077
0
}
3078
3079
bool ImGuiListClipper::Step()
3080
0
{
3081
0
    ImGuiContext& g = *Ctx;
3082
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3083
0
    bool ret = ImGuiListClipper_StepInternal(this);
3084
0
    if (ret && (DisplayStart == DisplayEnd))
3085
0
        ret = false;
3086
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3087
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3088
0
    if (need_items_height && ItemsHeight > 0.0f)
3089
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3090
0
    if (ret)
3091
0
    {
3092
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3093
0
    }
3094
0
    else
3095
0
    {
3096
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3097
0
        End();
3098
0
    }
3099
0
    return ret;
3100
0
}
3101
3102
//-----------------------------------------------------------------------------
3103
// [SECTION] STYLING
3104
//-----------------------------------------------------------------------------
3105
3106
ImGuiStyle& ImGui::GetStyle()
3107
11.7k
{
3108
11.7k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3109
11.7k
    return GImGui->Style;
3110
11.7k
}
3111
3112
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3113
400k
{
3114
400k
    ImGuiStyle& style = GImGui->Style;
3115
400k
    ImVec4 c = style.Colors[idx];
3116
400k
    c.w *= style.Alpha * alpha_mul;
3117
400k
    return ColorConvertFloat4ToU32(c);
3118
400k
}
3119
3120
ImU32 ImGui::GetColorU32(const ImVec4& col)
3121
0
{
3122
0
    ImGuiStyle& style = GImGui->Style;
3123
0
    ImVec4 c = col;
3124
0
    c.w *= style.Alpha;
3125
0
    return ColorConvertFloat4ToU32(c);
3126
0
}
3127
3128
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3129
0
{
3130
0
    ImGuiStyle& style = GImGui->Style;
3131
0
    return style.Colors[idx];
3132
0
}
3133
3134
ImU32 ImGui::GetColorU32(ImU32 col)
3135
0
{
3136
0
    ImGuiStyle& style = GImGui->Style;
3137
0
    if (style.Alpha >= 1.0f)
3138
0
        return col;
3139
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3140
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3141
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3142
0
}
3143
3144
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3145
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3146
0
{
3147
0
    ImGuiContext& g = *GImGui;
3148
0
    ImGuiColorMod backup;
3149
0
    backup.Col = idx;
3150
0
    backup.BackupValue = g.Style.Colors[idx];
3151
0
    g.ColorStack.push_back(backup);
3152
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3153
0
}
3154
3155
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3156
25.7k
{
3157
25.7k
    ImGuiContext& g = *GImGui;
3158
25.7k
    ImGuiColorMod backup;
3159
25.7k
    backup.Col = idx;
3160
25.7k
    backup.BackupValue = g.Style.Colors[idx];
3161
25.7k
    g.ColorStack.push_back(backup);
3162
25.7k
    g.Style.Colors[idx] = col;
3163
25.7k
}
3164
3165
void ImGui::PopStyleColor(int count)
3166
25.7k
{
3167
25.7k
    ImGuiContext& g = *GImGui;
3168
25.7k
    if (g.ColorStack.Size < count)
3169
0
    {
3170
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3171
0
        count = g.ColorStack.Size;
3172
0
    }
3173
51.5k
    while (count > 0)
3174
25.7k
    {
3175
25.7k
        ImGuiColorMod& backup = g.ColorStack.back();
3176
25.7k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3177
25.7k
        g.ColorStack.pop_back();
3178
25.7k
        count--;
3179
25.7k
    }
3180
25.7k
}
3181
3182
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3183
{
3184
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3185
};
3186
3187
static const ImGuiDataVarInfo GStyleVarInfo[] =
3188
{
3189
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                 // ImGuiStyleVar_Alpha
3190
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },         // ImGuiStyleVar_DisabledAlpha
3191
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },         // ImGuiStyleVar_WindowPadding
3192
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },        // ImGuiStyleVar_WindowRounding
3193
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },      // ImGuiStyleVar_WindowBorderSize
3194
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },         // ImGuiStyleVar_WindowMinSize
3195
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },      // ImGuiStyleVar_WindowTitleAlign
3196
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },         // ImGuiStyleVar_ChildRounding
3197
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },       // ImGuiStyleVar_ChildBorderSize
3198
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },         // ImGuiStyleVar_PopupRounding
3199
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },       // ImGuiStyleVar_PopupBorderSize
3200
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },          // ImGuiStyleVar_FramePadding
3201
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },         // ImGuiStyleVar_FrameRounding
3202
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },       // ImGuiStyleVar_FrameBorderSize
3203
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },           // ImGuiStyleVar_ItemSpacing
3204
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },      // ImGuiStyleVar_ItemInnerSpacing
3205
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },         // ImGuiStyleVar_IndentSpacing
3206
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },           // ImGuiStyleVar_CellPadding
3207
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },         // ImGuiStyleVar_ScrollbarSize
3208
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },     // ImGuiStyleVar_ScrollbarRounding
3209
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },           // ImGuiStyleVar_GrabMinSize
3210
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },          // ImGuiStyleVar_GrabRounding
3211
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },           // ImGuiStyleVar_TabRounding
3212
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },      // ImGuiStyleVar_TabBarBorderSize
3213
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },       // ImGuiStyleVar_ButtonTextAlign
3214
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },   // ImGuiStyleVar_SelectableTextAlign
3215
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3216
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },    // ImGuiStyleVar_SeparatorTextAlign
3217
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },  // ImGuiStyleVar_SeparatorTextPadding
3218
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },  // ImGuiStyleVar_DockingSeparatorSize
3219
};
3220
3221
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3222
51.5k
{
3223
51.5k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3224
51.5k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3225
51.5k
    return &GStyleVarInfo[idx];
3226
51.5k
}
3227
3228
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3229
0
{
3230
0
    ImGuiContext& g = *GImGui;
3231
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3232
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3233
0
    {
3234
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3235
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3236
0
        *pvar = val;
3237
0
        return;
3238
0
    }
3239
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3240
0
}
3241
3242
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3243
25.7k
{
3244
25.7k
    ImGuiContext& g = *GImGui;
3245
25.7k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3246
25.7k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3247
25.7k
    {
3248
25.7k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3249
25.7k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3250
25.7k
        *pvar = val;
3251
25.7k
        return;
3252
25.7k
    }
3253
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3254
0
}
3255
3256
void ImGui::PopStyleVar(int count)
3257
25.7k
{
3258
25.7k
    ImGuiContext& g = *GImGui;
3259
25.7k
    if (g.StyleVarStack.Size < count)
3260
0
    {
3261
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3262
0
        count = g.StyleVarStack.Size;
3263
0
    }
3264
51.5k
    while (count > 0)
3265
25.7k
    {
3266
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3267
25.7k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3268
25.7k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3269
25.7k
        void* data = info->GetVarPtr(&g.Style);
3270
25.7k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3271
25.7k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3272
25.7k
        g.StyleVarStack.pop_back();
3273
25.7k
        count--;
3274
25.7k
    }
3275
25.7k
}
3276
3277
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3278
0
{
3279
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3280
0
    switch (idx)
3281
0
    {
3282
0
    case ImGuiCol_Text: return "Text";
3283
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3284
0
    case ImGuiCol_WindowBg: return "WindowBg";
3285
0
    case ImGuiCol_ChildBg: return "ChildBg";
3286
0
    case ImGuiCol_PopupBg: return "PopupBg";
3287
0
    case ImGuiCol_Border: return "Border";
3288
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3289
0
    case ImGuiCol_FrameBg: return "FrameBg";
3290
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3291
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3292
0
    case ImGuiCol_TitleBg: return "TitleBg";
3293
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3294
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3295
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3296
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3297
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3298
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3299
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3300
0
    case ImGuiCol_CheckMark: return "CheckMark";
3301
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3302
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3303
0
    case ImGuiCol_Button: return "Button";
3304
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3305
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3306
0
    case ImGuiCol_Header: return "Header";
3307
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3308
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3309
0
    case ImGuiCol_Separator: return "Separator";
3310
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3311
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3312
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3313
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3314
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3315
0
    case ImGuiCol_Tab: return "Tab";
3316
0
    case ImGuiCol_TabHovered: return "TabHovered";
3317
0
    case ImGuiCol_TabActive: return "TabActive";
3318
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3319
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3320
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3321
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3322
0
    case ImGuiCol_PlotLines: return "PlotLines";
3323
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3324
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3325
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3326
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3327
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3328
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3329
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3330
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3331
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3332
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3333
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3334
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3335
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3336
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3337
0
    }
3338
0
    IM_ASSERT(0);
3339
0
    return "Unknown";
3340
0
}
3341
3342
3343
//-----------------------------------------------------------------------------
3344
// [SECTION] RENDER HELPERS
3345
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3346
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3347
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3348
//-----------------------------------------------------------------------------
3349
3350
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3351
103k
{
3352
103k
    const char* text_display_end = text;
3353
103k
    if (!text_end)
3354
103k
        text_end = (const char*)-1;
3355
3356
927k
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3357
824k
        text_display_end++;
3358
103k
    return text_display_end;
3359
103k
}
3360
3361
// Internal ImGui functions to render text
3362
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3363
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3364
0
{
3365
0
    ImGuiContext& g = *GImGui;
3366
0
    ImGuiWindow* window = g.CurrentWindow;
3367
3368
    // Hide anything after a '##' string
3369
0
    const char* text_display_end;
3370
0
    if (hide_text_after_hash)
3371
0
    {
3372
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3373
0
    }
3374
0
    else
3375
0
    {
3376
0
        if (!text_end)
3377
0
            text_end = text + strlen(text); // FIXME-OPT
3378
0
        text_display_end = text_end;
3379
0
    }
3380
3381
0
    if (text != text_display_end)
3382
0
    {
3383
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3384
0
        if (g.LogEnabled)
3385
0
            LogRenderedText(&pos, text, text_display_end);
3386
0
    }
3387
0
}
3388
3389
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3390
0
{
3391
0
    ImGuiContext& g = *GImGui;
3392
0
    ImGuiWindow* window = g.CurrentWindow;
3393
3394
0
    if (!text_end)
3395
0
        text_end = text + strlen(text); // FIXME-OPT
3396
3397
0
    if (text != text_end)
3398
0
    {
3399
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3400
0
        if (g.LogEnabled)
3401
0
            LogRenderedText(&pos, text, text_end);
3402
0
    }
3403
0
}
3404
3405
// Default clip_rect uses (pos_min,pos_max)
3406
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3407
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3408
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3409
// better advantage of the render function taking size into account for coarse clipping.
3410
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3411
51.5k
{
3412
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3413
51.5k
    ImVec2 pos = pos_min;
3414
51.5k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3415
3416
51.5k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3417
51.5k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3418
51.5k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3419
51.5k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3420
51.5k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3421
3422
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3423
51.5k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3424
51.5k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3425
3426
    // Render
3427
51.5k
    if (need_clipping)
3428
25.7k
    {
3429
25.7k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3430
25.7k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3431
25.7k
    }
3432
25.7k
    else
3433
25.7k
    {
3434
25.7k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3435
25.7k
    }
3436
51.5k
}
3437
3438
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3439
51.5k
{
3440
    // Hide anything after a '##' string
3441
51.5k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3442
51.5k
    const int text_len = (int)(text_display_end - text);
3443
51.5k
    if (text_len == 0)
3444
0
        return;
3445
3446
51.5k
    ImGuiContext& g = *GImGui;
3447
51.5k
    ImGuiWindow* window = g.CurrentWindow;
3448
51.5k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3449
51.5k
    if (g.LogEnabled)
3450
0
        LogRenderedText(&pos_min, text, text_display_end);
3451
51.5k
}
3452
3453
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3454
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3455
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3456
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3457
0
{
3458
0
    ImGuiContext& g = *GImGui;
3459
0
    if (text_end_full == NULL)
3460
0
        text_end_full = FindRenderedTextEnd(text);
3461
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3462
3463
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3464
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3465
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3466
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3467
0
    if (text_size.x > pos_max.x - pos_min.x)
3468
0
    {
3469
        // Hello wo...
3470
        // |       |   |
3471
        // min   max   ellipsis_max
3472
        //          <-> this is generally some padding value
3473
3474
0
        const ImFont* font = draw_list->_Data->Font;
3475
0
        const float font_size = draw_list->_Data->FontSize;
3476
0
        const float font_scale = font_size / font->FontSize;
3477
0
        const char* text_end_ellipsis = NULL;
3478
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3479
3480
        // We can now claim the space between pos_max.x and ellipsis_max.x
3481
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3482
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3483
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3484
0
        {
3485
            // Always display at least 1 character if there's no room for character + ellipsis
3486
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3487
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3488
0
        }
3489
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3490
0
        {
3491
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3492
0
            text_end_ellipsis--;
3493
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3494
0
        }
3495
3496
        // Render text, render ellipsis
3497
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3498
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3499
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3500
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3501
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3502
0
    }
3503
0
    else
3504
0
    {
3505
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3506
0
    }
3507
3508
0
    if (g.LogEnabled)
3509
0
        LogRenderedText(&pos_min, text, text_end_full);
3510
0
}
3511
3512
// Render a rectangle shaped with optional rounding and borders
3513
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3514
0
{
3515
0
    ImGuiContext& g = *GImGui;
3516
0
    ImGuiWindow* window = g.CurrentWindow;
3517
0
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3518
0
    const float border_size = g.Style.FrameBorderSize;
3519
0
    if (border && border_size > 0.0f)
3520
0
    {
3521
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3522
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3523
0
    }
3524
0
}
3525
3526
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3527
0
{
3528
0
    ImGuiContext& g = *GImGui;
3529
0
    ImGuiWindow* window = g.CurrentWindow;
3530
0
    const float border_size = g.Style.FrameBorderSize;
3531
0
    if (border_size > 0.0f)
3532
0
    {
3533
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3534
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3535
0
    }
3536
0
}
3537
3538
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3539
47.1k
{
3540
47.1k
    ImGuiContext& g = *GImGui;
3541
47.1k
    if (id != g.NavId)
3542
23.8k
        return;
3543
23.3k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3544
6.80k
        return;
3545
16.5k
    ImGuiWindow* window = g.CurrentWindow;
3546
16.5k
    if (window->DC.NavHideHighlightOneFrame)
3547
0
        return;
3548
3549
16.5k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3550
16.5k
    ImRect display_rect = bb;
3551
16.5k
    display_rect.ClipWith(window->ClipRect);
3552
16.5k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3553
875
    {
3554
875
        const float THICKNESS = 2.0f;
3555
875
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3556
875
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3557
875
        bool fully_visible = window->ClipRect.Contains(display_rect);
3558
875
        if (!fully_visible)
3559
2
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3560
875
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3561
875
        if (!fully_visible)
3562
2
            window->DrawList->PopClipRect();
3563
875
    }
3564
16.5k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3565
15.6k
    {
3566
15.6k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3567
15.6k
    }
3568
16.5k
}
3569
3570
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3571
0
{
3572
0
    ImGuiContext& g = *GImGui;
3573
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3574
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3575
0
    for (ImGuiViewportP* viewport : g.Viewports)
3576
0
    {
3577
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3578
0
        ImVec2 offset, size, uv[4];
3579
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3580
0
            continue;
3581
0
        const ImVec2 pos = base_pos - offset;
3582
0
        const float scale = base_scale * viewport->DpiScale;
3583
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3584
0
            continue;
3585
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3586
0
        ImTextureID tex_id = font_atlas->TexID;
3587
0
        draw_list->PushTextureID(tex_id);
3588
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3589
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3590
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3591
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3592
0
        draw_list->PopTextureID();
3593
0
    }
3594
0
}
3595
3596
//-----------------------------------------------------------------------------
3597
// [SECTION] INITIALIZATION, SHUTDOWN
3598
//-----------------------------------------------------------------------------
3599
3600
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3601
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3602
ImGuiContext* ImGui::GetCurrentContext()
3603
1
{
3604
1
    return GImGui;
3605
1
}
3606
3607
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3608
1
{
3609
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3610
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3611
#else
3612
1
    GImGui = ctx;
3613
1
#endif
3614
1
}
3615
3616
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3617
0
{
3618
0
    GImAllocatorAllocFunc = alloc_func;
3619
0
    GImAllocatorFreeFunc = free_func;
3620
0
    GImAllocatorUserData = user_data;
3621
0
}
3622
3623
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3624
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3625
0
{
3626
0
    *p_alloc_func = GImAllocatorAllocFunc;
3627
0
    *p_free_func = GImAllocatorFreeFunc;
3628
0
    *p_user_data = GImAllocatorUserData;
3629
0
}
3630
3631
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3632
1
{
3633
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3634
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3635
1
    SetCurrentContext(ctx);
3636
1
    Initialize();
3637
1
    if (prev_ctx != NULL)
3638
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3639
1
    return ctx;
3640
1
}
3641
3642
void ImGui::DestroyContext(ImGuiContext* ctx)
3643
0
{
3644
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3645
0
    if (ctx == NULL) //-V1051
3646
0
        ctx = prev_ctx;
3647
0
    SetCurrentContext(ctx);
3648
0
    Shutdown();
3649
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3650
0
    IM_DELETE(ctx);
3651
0
}
3652
3653
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3654
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3655
{
3656
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3657
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3658
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3659
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3660
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3661
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3662
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3663
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3664
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3665
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3666
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3667
};
3668
3669
void ImGui::Initialize()
3670
1
{
3671
1
    ImGuiContext& g = *GImGui;
3672
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3673
3674
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3675
1
    {
3676
1
        ImGuiSettingsHandler ini_handler;
3677
1
        ini_handler.TypeName = "Window";
3678
1
        ini_handler.TypeHash = ImHashStr("Window");
3679
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3680
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3681
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3682
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3683
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3684
1
        AddSettingsHandler(&ini_handler);
3685
1
    }
3686
1
    TableSettingsAddSettingsHandler();
3687
3688
    // Setup default localization table
3689
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3690
3691
    // Setup default platform clipboard/IME handlers.
3692
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3693
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3694
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3695
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3696
3697
    // Create default viewport
3698
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3699
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3700
1
    viewport->Idx = 0;
3701
1
    viewport->PlatformWindowCreated = true;
3702
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3703
1
    g.Viewports.push_back(viewport);
3704
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3705
1
    g.ViewportCreatedCount++;
3706
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3707
3708
1
#ifdef IMGUI_HAS_DOCK
3709
    // Initialize Docking
3710
1
    DockContextInitialize(&g);
3711
1
#endif
3712
3713
1
    g.Initialized = true;
3714
1
}
3715
3716
// This function is merely here to free heap allocations.
3717
void ImGui::Shutdown()
3718
0
{
3719
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3720
0
    ImGuiContext& g = *GImGui;
3721
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3722
0
    {
3723
0
        g.IO.Fonts->Locked = false;
3724
0
        IM_DELETE(g.IO.Fonts);
3725
0
    }
3726
0
    g.IO.Fonts = NULL;
3727
0
    g.DrawListSharedData.TempBuffer.clear();
3728
3729
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3730
0
    if (!g.Initialized)
3731
0
        return;
3732
3733
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3734
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3735
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3736
3737
    // Destroy platform windows
3738
0
    DestroyPlatformWindows();
3739
3740
    // Shutdown extensions
3741
0
    DockContextShutdown(&g);
3742
3743
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3744
3745
    // Clear everything else
3746
0
    g.Windows.clear_delete();
3747
0
    g.WindowsFocusOrder.clear();
3748
0
    g.WindowsTempSortBuffer.clear();
3749
0
    g.CurrentWindow = NULL;
3750
0
    g.CurrentWindowStack.clear();
3751
0
    g.WindowsById.Clear();
3752
0
    g.NavWindow = NULL;
3753
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3754
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3755
0
    g.MovingWindow = NULL;
3756
3757
0
    g.KeysRoutingTable.Clear();
3758
3759
0
    g.ColorStack.clear();
3760
0
    g.StyleVarStack.clear();
3761
0
    g.FontStack.clear();
3762
0
    g.OpenPopupStack.clear();
3763
0
    g.BeginPopupStack.clear();
3764
0
    g.NavTreeNodeStack.clear();
3765
3766
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3767
0
    g.Viewports.clear_delete();
3768
3769
0
    g.TabBars.Clear();
3770
0
    g.CurrentTabBarStack.clear();
3771
0
    g.ShrinkWidthBuffer.clear();
3772
3773
0
    g.ClipperTempData.clear_destruct();
3774
3775
0
    g.Tables.Clear();
3776
0
    g.TablesTempData.clear_destruct();
3777
0
    g.DrawChannelsTempMergeBuffer.clear();
3778
3779
0
    g.ClipboardHandlerData.clear();
3780
0
    g.MenusIdSubmittedThisFrame.clear();
3781
0
    g.InputTextState.ClearFreeMemory();
3782
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3783
3784
0
    g.SettingsWindows.clear();
3785
0
    g.SettingsHandlers.clear();
3786
3787
0
    if (g.LogFile)
3788
0
    {
3789
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3790
0
        if (g.LogFile != stdout)
3791
0
#endif
3792
0
            ImFileClose(g.LogFile);
3793
0
        g.LogFile = NULL;
3794
0
    }
3795
0
    g.LogBuffer.clear();
3796
0
    g.DebugLogBuf.clear();
3797
0
    g.DebugLogIndex.clear();
3798
3799
0
    g.Initialized = false;
3800
0
}
3801
3802
// No specific ordering/dependency support, will see as needed
3803
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3804
0
{
3805
0
    ImGuiContext& g = *ctx;
3806
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3807
0
    g.Hooks.push_back(*hook);
3808
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3809
0
    return g.HookIdNext;
3810
0
}
3811
3812
// Deferred removal, avoiding issue with changing vector while iterating it
3813
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3814
0
{
3815
0
    ImGuiContext& g = *ctx;
3816
0
    IM_ASSERT(hook_id != 0);
3817
0
    for (ImGuiContextHook& hook : g.Hooks)
3818
0
        if (hook.HookId == hook_id)
3819
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3820
0
}
3821
3822
// Call context hooks (used by e.g. test engine)
3823
// We assume a small number of hooks so all stored in same array
3824
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3825
154k
{
3826
154k
    ImGuiContext& g = *ctx;
3827
154k
    for (ImGuiContextHook& hook : g.Hooks)
3828
0
        if (hook.Type == hook_type)
3829
0
            hook.Callback(&g, &hook);
3830
154k
}
3831
3832
3833
//-----------------------------------------------------------------------------
3834
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3835
//-----------------------------------------------------------------------------
3836
3837
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3838
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3839
3
{
3840
3
    memset(this, 0, sizeof(*this));
3841
3
    Ctx = ctx;
3842
3
    Name = ImStrdup(name);
3843
3
    NameBufLen = (int)strlen(name) + 1;
3844
3
    ID = ImHashStr(name);
3845
3
    IDStack.push_back(ID);
3846
3
    ViewportAllowPlatformMonitorExtend = -1;
3847
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3848
3
    MoveId = GetID("#MOVE");
3849
3
    TabId = GetID("#TAB");
3850
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3851
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3852
3
    AutoFitFramesX = AutoFitFramesY = -1;
3853
3
    AutoPosLastDirection = ImGuiDir_None;
3854
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3855
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3856
3
    LastFrameActive = -1;
3857
3
    LastFrameJustFocused = -1;
3858
3
    LastTimeActive = -1.0f;
3859
3
    FontWindowScale = FontDpiScale = 1.0f;
3860
3
    SettingsOffset = -1;
3861
3
    DockOrder = -1;
3862
3
    DrawList = &DrawListInst;
3863
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3864
3
    DrawList->_OwnerName = Name;
3865
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3866
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3867
3
}
3868
3869
ImGuiWindow::~ImGuiWindow()
3870
0
{
3871
0
    IM_ASSERT(DrawList == &DrawListInst);
3872
0
    IM_DELETE(Name);
3873
0
    ColumnsStorage.clear_destruct();
3874
0
}
3875
3876
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3877
155k
{
3878
155k
    ImGuiID seed = IDStack.back();
3879
155k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3880
155k
    ImGuiContext& g = *Ctx;
3881
155k
    if (g.DebugHookIdInfo == id)
3882
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3883
155k
    return id;
3884
155k
}
3885
3886
ImGuiID ImGuiWindow::GetID(const void* ptr)
3887
0
{
3888
0
    ImGuiID seed = IDStack.back();
3889
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3890
0
    ImGuiContext& g = *Ctx;
3891
0
    if (g.DebugHookIdInfo == id)
3892
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3893
0
    return id;
3894
0
}
3895
3896
ImGuiID ImGuiWindow::GetID(int n)
3897
25.7k
{
3898
25.7k
    ImGuiID seed = IDStack.back();
3899
25.7k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3900
25.7k
    ImGuiContext& g = *Ctx;
3901
25.7k
    if (g.DebugHookIdInfo == id)
3902
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3903
25.7k
    return id;
3904
25.7k
}
3905
3906
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3907
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3908
0
{
3909
0
    ImGuiID seed = IDStack.back();
3910
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3911
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3912
0
    return id;
3913
0
}
3914
3915
static void SetCurrentWindow(ImGuiWindow* window)
3916
154k
{
3917
154k
    ImGuiContext& g = *GImGui;
3918
154k
    g.CurrentWindow = window;
3919
154k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3920
154k
    if (window)
3921
128k
    {
3922
128k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3923
128k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3924
128k
    }
3925
154k
}
3926
3927
void ImGui::GcCompactTransientMiscBuffers()
3928
0
{
3929
0
    ImGuiContext& g = *GImGui;
3930
0
    g.ItemFlagsStack.clear();
3931
0
    g.GroupStack.clear();
3932
0
    TableGcCompactSettings();
3933
0
}
3934
3935
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3936
// Not freed:
3937
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3938
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3939
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3940
0
{
3941
0
    window->MemoryCompacted = true;
3942
0
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3943
0
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3944
0
    window->IDStack.clear();
3945
0
    window->DrawList->_ClearFreeMemory();
3946
0
    window->DC.ChildWindows.clear();
3947
0
    window->DC.ItemWidthStack.clear();
3948
0
    window->DC.TextWrapPosStack.clear();
3949
0
}
3950
3951
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3952
0
{
3953
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3954
    // The other buffers tends to amortize much faster.
3955
0
    window->MemoryCompacted = false;
3956
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3957
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3958
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3959
0
}
3960
3961
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3962
195
{
3963
195
    ImGuiContext& g = *GImGui;
3964
3965
    // Clear previous active id
3966
195
    if (g.ActiveId != 0)
3967
12
    {
3968
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3969
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3970
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3971
12
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3972
0
        {
3973
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3974
0
            g.MovingWindow = NULL;
3975
0
        }
3976
3977
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3978
        // but since this is currently quite an exception we'll leave it as is.
3979
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3980
12
        if (g.InputTextState.ID == g.ActiveId)
3981
0
            InputTextDeactivateHook(g.ActiveId);
3982
12
    }
3983
3984
    // Set active id
3985
195
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3986
195
    if (g.ActiveIdIsJustActivated)
3987
24
    {
3988
24
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3989
24
        g.ActiveIdTimer = 0.0f;
3990
24
        g.ActiveIdHasBeenPressedBefore = false;
3991
24
        g.ActiveIdHasBeenEditedBefore = false;
3992
24
        g.ActiveIdMouseButton = -1;
3993
24
        if (id != 0)
3994
12
        {
3995
12
            g.LastActiveId = id;
3996
12
            g.LastActiveIdTimer = 0.0f;
3997
12
        }
3998
24
    }
3999
195
    g.ActiveId = id;
4000
195
    g.ActiveIdAllowOverlap = false;
4001
195
    g.ActiveIdNoClearOnFocusLoss = false;
4002
195
    g.ActiveIdWindow = window;
4003
195
    g.ActiveIdHasBeenEditedThisFrame = false;
4004
195
    if (id)
4005
12
    {
4006
12
        g.ActiveIdIsAlive = id;
4007
12
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4008
12
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4009
12
    }
4010
4011
    // Clear declaration of inputs claimed by the widget
4012
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4013
195
    g.ActiveIdUsingNavDirMask = 0x00;
4014
195
    g.ActiveIdUsingAllKeyboardKeys = false;
4015
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4016
    g.ActiveIdUsingNavInputMask = 0x00;
4017
#endif
4018
195
}
4019
4020
void ImGui::ClearActiveID()
4021
183
{
4022
183
    SetActiveID(0, NULL); // g.ActiveId = 0;
4023
183
}
4024
4025
void ImGui::SetHoveredID(ImGuiID id)
4026
1.40k
{
4027
1.40k
    ImGuiContext& g = *GImGui;
4028
1.40k
    g.HoveredId = id;
4029
1.40k
    g.HoveredIdAllowOverlap = false;
4030
1.40k
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4031
464
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4032
1.40k
}
4033
4034
ImGuiID ImGui::GetHoveredID()
4035
0
{
4036
0
    ImGuiContext& g = *GImGui;
4037
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4038
0
}
4039
4040
// This is called by ItemAdd().
4041
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
4042
void ImGui::KeepAliveID(ImGuiID id)
4043
109k
{
4044
109k
    ImGuiContext& g = *GImGui;
4045
109k
    if (g.ActiveId == id)
4046
142
        g.ActiveIdIsAlive = id;
4047
109k
    if (g.ActiveIdPreviousFrame == id)
4048
142
        g.ActiveIdPreviousFrameIsAlive = true;
4049
109k
}
4050
4051
void ImGui::MarkItemEdited(ImGuiID id)
4052
0
{
4053
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4054
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4055
0
    ImGuiContext& g = *GImGui;
4056
0
    if (g.LockMarkEdited > 0)
4057
0
        return;
4058
0
    if (g.ActiveId == id || g.ActiveId == 0)
4059
0
    {
4060
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4061
0
        g.ActiveIdHasBeenEditedBefore = true;
4062
0
    }
4063
4064
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4065
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4066
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
4067
4068
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4069
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4070
0
}
4071
4072
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4073
1.40k
{
4074
    // An active popup disable hovering on other windows (apart from its own children)
4075
    // FIXME-OPT: This could be cached/stored within the window.
4076
1.40k
    ImGuiContext& g = *GImGui;
4077
1.40k
    if (g.NavWindow)
4078
1.40k
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4079
1.40k
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4080
0
            {
4081
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4082
                // NB: The 'else' is important because Modal windows are also Popups.
4083
0
                bool want_inhibit = false;
4084
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4085
0
                    want_inhibit = true;
4086
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4087
0
                    want_inhibit = true;
4088
4089
                // Inhibit hover unless the window is within the stack of our modal/popup
4090
0
                if (want_inhibit)
4091
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4092
0
                        return false;
4093
0
            }
4094
4095
    // Filter by viewport
4096
1.40k
    if (window->Viewport != g.MouseViewport)
4097
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4098
0
            return false;
4099
4100
1.40k
    return true;
4101
1.40k
}
4102
4103
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4104
0
{
4105
0
    ImGuiContext& g = *GImGui;
4106
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4107
0
        return g.Style.HoverDelayNormal;
4108
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4109
0
        return g.Style.HoverDelayShort;
4110
0
    return 0.0f;
4111
0
}
4112
4113
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4114
0
{
4115
    // Allow instance flags to override shared flags
4116
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4117
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4118
0
    return user_flags | shared_flags;
4119
0
}
4120
4121
// This is roughly matching the behavior of internal-facing ItemHoverable()
4122
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4123
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4124
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4125
0
{
4126
0
    ImGuiContext& g = *GImGui;
4127
0
    ImGuiWindow* window = g.CurrentWindow;
4128
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4129
4130
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4131
0
    {
4132
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4133
0
            return false;
4134
0
        if (!IsItemFocused())
4135
0
            return false;
4136
4137
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4138
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4139
0
    }
4140
0
    else
4141
0
    {
4142
        // Test for bounding box overlap, as updated as ItemAdd()
4143
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4144
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4145
0
            return false;
4146
4147
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4148
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4149
4150
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4151
4152
        // Done with rectangle culling so we can perform heavier checks now
4153
        // Test if we are hovering the right window (our window could be behind another window)
4154
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4155
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4156
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4157
        // the test that has been running for a long while.
4158
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4159
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4160
0
                return false;
4161
4162
        // Test if another item is active (e.g. being dragged)
4163
0
        const ImGuiID id = g.LastItemData.ID;
4164
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4165
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4166
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4167
0
                    return false;
4168
4169
        // Test if interactions on this window are blocked by an active popup or modal.
4170
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4171
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4172
0
            return false;
4173
4174
        // Test if the item is disabled
4175
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4176
0
            return false;
4177
4178
        // Special handling for calling after Begin() which represent the title bar or tab.
4179
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4180
        // will never be overwritten so we need to detect the case.
4181
0
        if (id == window->MoveId && window->WriteAccessed)
4182
0
            return false;
4183
4184
        // Test if using AllowOverlap and overlapped
4185
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4186
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4187
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4188
0
                    return false;
4189
0
    }
4190
4191
    // Handle hover delay
4192
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4193
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4194
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4195
0
    {
4196
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4197
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4198
0
            g.HoverItemDelayTimer = 0.0f;
4199
0
        g.HoverItemDelayId = hover_delay_id;
4200
4201
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4202
        // but once unlocked on a given item we also moving.
4203
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4204
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4205
0
            return false;
4206
4207
0
        if (g.HoverItemDelayTimer < delay)
4208
0
            return false;
4209
0
    }
4210
4211
0
    return true;
4212
0
}
4213
4214
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4215
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4216
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4217
// If you used this in your legacy/custom widgets code:
4218
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4219
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4220
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4221
84.9k
{
4222
84.9k
    ImGuiContext& g = *GImGui;
4223
84.9k
    ImGuiWindow* window = g.CurrentWindow;
4224
84.9k
    if (g.HoveredWindow != window)
4225
79.5k
        return false;
4226
5.38k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4227
3.98k
        return false;
4228
4229
1.40k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4230
0
        return false;
4231
1.40k
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4232
0
        return false;
4233
4234
    // Done with rectangle culling so we can perform heavier checks now.
4235
1.40k
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4236
0
    {
4237
0
        g.HoveredIdDisabled = true;
4238
0
        return false;
4239
0
    }
4240
4241
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4242
    // hover test in widgets code. We could also decide to split this function is two.
4243
1.40k
    if (id != 0)
4244
1.40k
    {
4245
        // Drag source doesn't report as hovered
4246
1.40k
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4247
0
            return false;
4248
4249
1.40k
        SetHoveredID(id);
4250
4251
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4252
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4253
1.40k
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4254
0
        {
4255
0
            g.HoveredIdAllowOverlap = true;
4256
0
            if (g.HoveredIdPreviousFrame != id)
4257
0
                return false;
4258
0
        }
4259
1.40k
    }
4260
4261
    // When disabled we'll return false but still set HoveredId
4262
1.40k
    if (item_flags & ImGuiItemFlags_Disabled)
4263
0
    {
4264
        // Release active id if turning disabled
4265
0
        if (g.ActiveId == id && id != 0)
4266
0
            ClearActiveID();
4267
0
        g.HoveredIdDisabled = true;
4268
0
        return false;
4269
0
    }
4270
4271
1.40k
    if (id != 0)
4272
1.40k
    {
4273
        // [DEBUG] Item Picker tool!
4274
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4275
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4276
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4277
1.40k
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4278
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4279
1.40k
        if (g.DebugItemPickerBreakId == id)
4280
0
            IM_DEBUG_BREAK();
4281
1.40k
    }
4282
4283
1.40k
    if (g.NavDisableMouseHover)
4284
163
        return false;
4285
4286
1.23k
    return true;
4287
1.40k
}
4288
4289
// FIXME: This is inlined/duplicated in ItemAdd()
4290
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4291
0
{
4292
0
    ImGuiContext& g = *GImGui;
4293
0
    ImGuiWindow* window = g.CurrentWindow;
4294
0
    if (!bb.Overlaps(window->ClipRect))
4295
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4296
0
            if (!g.LogEnabled)
4297
0
                return true;
4298
0
    return false;
4299
0
}
4300
4301
// This is also inlined in ItemAdd()
4302
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4303
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4304
77.3k
{
4305
77.3k
    ImGuiContext& g = *GImGui;
4306
77.3k
    g.LastItemData.ID = item_id;
4307
77.3k
    g.LastItemData.InFlags = in_flags;
4308
77.3k
    g.LastItemData.StatusFlags = item_flags;
4309
77.3k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4310
77.3k
}
4311
4312
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4313
0
{
4314
0
    if (wrap_pos_x < 0.0f)
4315
0
        return 0.0f;
4316
4317
0
    ImGuiContext& g = *GImGui;
4318
0
    ImGuiWindow* window = g.CurrentWindow;
4319
0
    if (wrap_pos_x == 0.0f)
4320
0
    {
4321
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4322
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4323
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4324
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4325
        //else
4326
0
        wrap_pos_x = window->WorkRect.Max.x;
4327
0
    }
4328
0
    else if (wrap_pos_x > 0.0f)
4329
0
    {
4330
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4331
0
    }
4332
4333
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4334
0
}
4335
4336
// IM_ALLOC() == ImGui::MemAlloc()
4337
void* ImGui::MemAlloc(size_t size)
4338
1.23k
{
4339
1.23k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4340
1.23k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4341
1.23k
    if (ImGuiContext* ctx = GImGui)
4342
1.23k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4343
1.23k
#endif
4344
1.23k
    return ptr;
4345
1.23k
}
4346
4347
// IM_FREE() == ImGui::MemFree()
4348
void ImGui::MemFree(void* ptr)
4349
1.18k
{
4350
1.18k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4351
1.18k
    if (ptr != NULL)
4352
1.17k
        if (ImGuiContext* ctx = GImGui)
4353
1.17k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4354
1.18k
#endif
4355
1.18k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4356
1.18k
}
4357
4358
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4359
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4360
2.40k
{
4361
2.40k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4362
2.40k
    IM_UNUSED(ptr);
4363
2.40k
    if (entry->FrameCount != frame_count)
4364
17
    {
4365
17
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4366
17
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4367
17
        entry->FrameCount = frame_count;
4368
17
        entry->AllocCount = entry->FreeCount = 0;
4369
17
    }
4370
2.40k
    if (size != (size_t)-1)
4371
1.23k
    {
4372
1.23k
        entry->AllocCount++;
4373
1.23k
        info->TotalAllocCount++;
4374
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4375
1.23k
    }
4376
1.17k
    else
4377
1.17k
    {
4378
1.17k
        entry->FreeCount++;
4379
1.17k
        info->TotalFreeCount++;
4380
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4381
1.17k
    }
4382
2.40k
}
4383
4384
const char* ImGui::GetClipboardText()
4385
0
{
4386
0
    ImGuiContext& g = *GImGui;
4387
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4388
0
}
4389
4390
void ImGui::SetClipboardText(const char* text)
4391
0
{
4392
0
    ImGuiContext& g = *GImGui;
4393
0
    if (g.IO.SetClipboardTextFn)
4394
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4395
0
}
4396
4397
const char* ImGui::GetVersion()
4398
0
{
4399
0
    return IMGUI_VERSION;
4400
0
}
4401
4402
ImGuiIO& ImGui::GetIO()
4403
82.6k
{
4404
82.6k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4405
82.6k
    return GImGui->IO;
4406
82.6k
}
4407
4408
ImGuiPlatformIO& ImGui::GetPlatformIO()
4409
0
{
4410
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4411
0
    return GImGui->PlatformIO;
4412
0
}
4413
4414
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4415
ImDrawData* ImGui::GetDrawData()
4416
25.7k
{
4417
25.7k
    ImGuiContext& g = *GImGui;
4418
25.7k
    ImGuiViewportP* viewport = g.Viewports[0];
4419
25.7k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4420
25.7k
}
4421
4422
double ImGui::GetTime()
4423
0
{
4424
0
    return GImGui->Time;
4425
0
}
4426
4427
int ImGui::GetFrameCount()
4428
0
{
4429
0
    return GImGui->FrameCount;
4430
0
}
4431
4432
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4433
0
{
4434
    // Create the draw list on demand, because they are not frequently used for all viewports
4435
0
    ImGuiContext& g = *GImGui;
4436
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4437
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4438
0
    if (draw_list == NULL)
4439
0
    {
4440
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4441
0
        draw_list->_OwnerName = drawlist_name;
4442
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4443
0
    }
4444
4445
    // Our ImDrawList system requires that there is always a command
4446
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4447
0
    {
4448
0
        draw_list->_ResetForNewFrame();
4449
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4450
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4451
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4452
0
    }
4453
0
    return draw_list;
4454
0
}
4455
4456
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4457
0
{
4458
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4459
0
}
4460
4461
ImDrawList* ImGui::GetBackgroundDrawList()
4462
0
{
4463
0
    ImGuiContext& g = *GImGui;
4464
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4465
0
}
4466
4467
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4468
0
{
4469
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4470
0
}
4471
4472
ImDrawList* ImGui::GetForegroundDrawList()
4473
0
{
4474
0
    ImGuiContext& g = *GImGui;
4475
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4476
0
}
4477
4478
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4479
0
{
4480
0
    return &GImGui->DrawListSharedData;
4481
0
}
4482
4483
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4484
0
{
4485
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4486
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4487
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4488
0
    ImGuiContext& g = *GImGui;
4489
0
    FocusWindow(window);
4490
0
    SetActiveID(window->MoveId, window);
4491
0
    g.NavDisableHighlight = true;
4492
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4493
0
    g.ActiveIdNoClearOnFocusLoss = true;
4494
0
    SetActiveIdUsingAllKeyboardKeys();
4495
4496
0
    bool can_move_window = true;
4497
0
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4498
0
        can_move_window = false;
4499
0
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4500
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4501
0
            can_move_window = false;
4502
0
    if (can_move_window)
4503
0
        g.MovingWindow = window;
4504
0
}
4505
4506
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4507
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4508
0
{
4509
0
    ImGuiContext& g = *GImGui;
4510
0
    bool can_undock_node = false;
4511
0
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4512
0
    {
4513
        // Can undock if:
4514
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4515
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4516
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4517
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4518
0
            can_undock_node = true;
4519
0
    }
4520
4521
0
    const bool clicked = IsMouseClicked(0);
4522
0
    const bool dragging = IsMouseDragging(0);
4523
0
    if (can_undock_node && dragging)
4524
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4525
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4526
0
        StartMouseMovingWindow(window);
4527
0
}
4528
4529
// Handle mouse moving window
4530
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4531
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4532
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4533
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4534
void ImGui::UpdateMouseMovingWindowNewFrame()
4535
25.7k
{
4536
25.7k
    ImGuiContext& g = *GImGui;
4537
25.7k
    if (g.MovingWindow != NULL)
4538
0
    {
4539
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4540
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4541
0
        KeepAliveID(g.ActiveId);
4542
0
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4543
0
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4544
4545
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4546
0
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4547
0
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4548
0
        {
4549
0
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4550
0
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4551
0
            {
4552
0
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4553
0
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4554
0
                {
4555
0
                    moving_window->Viewport->Pos = pos;
4556
0
                    moving_window->Viewport->UpdateWorkRect();
4557
0
                }
4558
0
            }
4559
0
            FocusWindow(g.MovingWindow);
4560
0
        }
4561
0
        else
4562
0
        {
4563
0
            if (!window_disappared)
4564
0
            {
4565
                // Try to merge the window back into the main viewport.
4566
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4567
0
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4568
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4569
4570
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4571
0
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4572
0
                    g.MouseViewport = moving_window->Viewport;
4573
4574
                // Clear the NoInput window flag set by the Viewport system
4575
0
                if (moving_window->Viewport)
4576
0
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4577
0
            }
4578
4579
0
            g.MovingWindow = NULL;
4580
0
            ClearActiveID();
4581
0
        }
4582
0
    }
4583
25.7k
    else
4584
25.7k
    {
4585
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4586
25.7k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4587
0
        {
4588
0
            KeepAliveID(g.ActiveId);
4589
0
            if (!g.IO.MouseDown[0])
4590
0
                ClearActiveID();
4591
0
        }
4592
25.7k
    }
4593
25.7k
}
4594
4595
// Initiate moving window when clicking on empty space or title bar.
4596
// Handle left-click and right-click focus.
4597
void ImGui::UpdateMouseMovingWindowEndFrame()
4598
25.7k
{
4599
25.7k
    ImGuiContext& g = *GImGui;
4600
25.7k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4601
1.40k
        return;
4602
4603
    // Unless we just made a window/popup appear
4604
24.3k
    if (g.NavWindow && g.NavWindow->Appearing)
4605
1
        return;
4606
4607
    // Click on empty space to focus window and start moving
4608
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4609
24.3k
    if (g.IO.MouseClicked[0])
4610
782
    {
4611
        // Handle the edge case of a popup being closed while clicking in its empty space.
4612
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4613
782
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4614
782
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4615
4616
782
        if (root_window != NULL && !is_closed_popup)
4617
0
        {
4618
0
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4619
4620
            // Cancel moving if clicked outside of title bar
4621
0
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4622
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4623
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4624
0
                        g.MovingWindow = NULL;
4625
4626
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4627
0
            if (g.HoveredIdDisabled)
4628
0
                g.MovingWindow = NULL;
4629
0
        }
4630
782
        else if (root_window == NULL && g.NavWindow != NULL)
4631
599
        {
4632
            // Clicking on void disable focus
4633
599
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4634
599
        }
4635
782
    }
4636
4637
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4638
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4639
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4640
24.3k
    if (g.IO.MouseClicked[1])
4641
2
    {
4642
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4643
        // This is where we can trim the popup stack.
4644
2
        ImGuiWindow* modal = GetTopMostPopupModal();
4645
2
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4646
2
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4647
2
    }
4648
24.3k
}
4649
4650
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4651
// Need to keep in sync with SetWindowPos()
4652
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4653
0
{
4654
0
    window->Pos += delta;
4655
0
    window->ClipRect.Translate(delta);
4656
0
    window->OuterRectClipped.Translate(delta);
4657
0
    window->InnerRect.Translate(delta);
4658
0
    window->DC.CursorPos += delta;
4659
0
    window->DC.CursorStartPos += delta;
4660
0
    window->DC.CursorMaxPos += delta;
4661
0
    window->DC.IdealMaxPos += delta;
4662
0
}
4663
4664
static void ScaleWindow(ImGuiWindow* window, float scale)
4665
0
{
4666
0
    ImVec2 origin = window->Viewport->Pos;
4667
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4668
0
    window->Size = ImTrunc(window->Size * scale);
4669
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4670
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4671
0
}
4672
4673
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4674
103k
{
4675
103k
    return (window->Active) && (!window->Hidden);
4676
103k
}
4677
4678
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4679
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4680
25.7k
{
4681
25.7k
    ImGuiContext& g = *GImGui;
4682
25.7k
    ImGuiIO& io = g.IO;
4683
25.7k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4684
4685
    // Find the window hovered by mouse:
4686
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4687
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4688
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4689
25.7k
    bool clear_hovered_windows = false;
4690
25.7k
    FindHoveredWindow();
4691
25.7k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4692
4693
    // Modal windows prevents mouse from hovering behind them.
4694
25.7k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4695
25.7k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4696
0
        clear_hovered_windows = true;
4697
4698
    // Disabled mouse?
4699
25.7k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4700
0
        clear_hovered_windows = true;
4701
4702
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4703
    // won't report hovering nor request capture even while dragging over our windows afterward.
4704
25.7k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4705
25.7k
    const bool has_open_modal = (modal_window != NULL);
4706
25.7k
    int mouse_earliest_down = -1;
4707
25.7k
    bool mouse_any_down = false;
4708
154k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4709
128k
    {
4710
128k
        if (io.MouseClicked[i])
4711
849
        {
4712
849
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4713
849
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4714
849
        }
4715
128k
        mouse_any_down |= io.MouseDown[i];
4716
128k
        if (io.MouseDown[i])
4717
1.67k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4718
1.47k
                mouse_earliest_down = i;
4719
128k
    }
4720
25.7k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4721
25.7k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4722
4723
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4724
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4725
25.7k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4726
25.7k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4727
1.21k
        clear_hovered_windows = true;
4728
4729
25.7k
    if (clear_hovered_windows)
4730
1.21k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4731
4732
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4733
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4734
25.7k
    if (g.WantCaptureMouseNextFrame != -1)
4735
0
    {
4736
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4737
0
    }
4738
25.7k
    else
4739
25.7k
    {
4740
25.7k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4741
25.7k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4742
25.7k
    }
4743
4744
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4745
25.7k
    if (g.WantCaptureKeyboardNextFrame != -1)
4746
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4747
25.7k
    else
4748
25.7k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4749
25.7k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4750
23.1k
        io.WantCaptureKeyboard = true;
4751
4752
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4753
25.7k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4754
25.7k
}
4755
4756
void ImGui::NewFrame()
4757
25.7k
{
4758
25.7k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4759
25.7k
    ImGuiContext& g = *GImGui;
4760
4761
    // Remove pending delete hooks before frame start.
4762
    // This deferred removal avoid issues of removal while iterating the hook vector
4763
25.7k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4764
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4765
0
            g.Hooks.erase(&g.Hooks[n]);
4766
4767
25.7k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4768
4769
    // Check and assert for various common IO and Configuration mistakes
4770
25.7k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4771
25.7k
    ErrorCheckNewFrameSanityChecks();
4772
25.7k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4773
4774
    // Load settings on first frame, save settings when modified (after a delay)
4775
25.7k
    UpdateSettings();
4776
4777
25.7k
    g.Time += g.IO.DeltaTime;
4778
25.7k
    g.WithinFrameScope = true;
4779
25.7k
    g.FrameCount += 1;
4780
25.7k
    g.TooltipOverrideCount = 0;
4781
25.7k
    g.WindowsActiveCount = 0;
4782
25.7k
    g.MenusIdSubmittedThisFrame.resize(0);
4783
4784
    // Calculate frame-rate for the user, as a purely luxurious feature
4785
25.7k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4786
25.7k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4787
25.7k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4788
25.7k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4789
25.7k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4790
4791
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4792
25.7k
    g.InputEventsTrail.resize(0);
4793
25.7k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4794
4795
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4796
25.7k
    UpdateViewportsNewFrame();
4797
4798
    // Setup current font and draw list shared data
4799
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4800
25.7k
    g.IO.Fonts->Locked = true;
4801
25.7k
    SetCurrentFont(GetDefaultFont());
4802
25.7k
    IM_ASSERT(g.Font->IsLoaded());
4803
25.7k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4804
25.7k
    for (ImGuiViewportP* viewport : g.Viewports)
4805
25.7k
        virtual_space.Add(viewport->GetMainRect());
4806
25.7k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4807
25.7k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4808
25.7k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4809
25.7k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4810
25.7k
    if (g.Style.AntiAliasedLines)
4811
25.7k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4812
25.7k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4813
25.7k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4814
25.7k
    if (g.Style.AntiAliasedFill)
4815
25.7k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4816
25.7k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4817
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4818
4819
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4820
25.7k
    for (ImGuiViewportP* viewport : g.Viewports)
4821
25.7k
    {
4822
25.7k
        viewport->DrawData = NULL;
4823
25.7k
        viewport->DrawDataP.Valid = false;
4824
25.7k
    }
4825
4826
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4827
25.7k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4828
0
        KeepAliveID(g.DragDropPayload.SourceId);
4829
4830
    // Update HoveredId data
4831
25.7k
    if (!g.HoveredIdPreviousFrame)
4832
24.3k
        g.HoveredIdTimer = 0.0f;
4833
25.7k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4834
24.5k
        g.HoveredIdNotActiveTimer = 0.0f;
4835
25.7k
    if (g.HoveredId)
4836
1.40k
        g.HoveredIdTimer += g.IO.DeltaTime;
4837
25.7k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4838
1.26k
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4839
25.7k
    g.HoveredIdPreviousFrame = g.HoveredId;
4840
25.7k
    g.HoveredId = 0;
4841
25.7k
    g.HoveredIdAllowOverlap = false;
4842
25.7k
    g.HoveredIdDisabled = false;
4843
4844
    // Clear ActiveID if the item is not alive anymore.
4845
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4846
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4847
25.7k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4848
0
    {
4849
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4850
0
        ClearActiveID();
4851
0
    }
4852
4853
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4854
25.7k
    if (g.ActiveId)
4855
142
        g.ActiveIdTimer += g.IO.DeltaTime;
4856
25.7k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4857
25.7k
    g.ActiveIdPreviousFrame = g.ActiveId;
4858
25.7k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4859
25.7k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4860
25.7k
    g.ActiveIdIsAlive = 0;
4861
25.7k
    g.ActiveIdHasBeenEditedThisFrame = false;
4862
25.7k
    g.ActiveIdPreviousFrameIsAlive = false;
4863
25.7k
    g.ActiveIdIsJustActivated = false;
4864
25.7k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4865
0
        g.TempInputId = 0;
4866
25.7k
    if (g.ActiveId == 0)
4867
25.6k
    {
4868
25.6k
        g.ActiveIdUsingNavDirMask = 0x00;
4869
25.6k
        g.ActiveIdUsingAllKeyboardKeys = false;
4870
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4871
        g.ActiveIdUsingNavInputMask = 0x00;
4872
#endif
4873
25.6k
    }
4874
4875
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4876
    if (g.ActiveId == 0)
4877
        g.ActiveIdUsingNavInputMask = 0;
4878
    else if (g.ActiveIdUsingNavInputMask != 0)
4879
    {
4880
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4881
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4882
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4883
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4884
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4885
            IM_ASSERT(0); // Other values unsupported
4886
    }
4887
#endif
4888
4889
    // Record when we have been stationary as this state is preserved while over same item.
4890
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4891
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4892
25.7k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4893
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4894
25.7k
    else if (g.HoverItemDelayId == 0)
4895
25.7k
        g.HoverItemUnlockedStationaryId = 0;
4896
25.7k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4897
1.64k
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4898
24.1k
    else if (g.HoveredWindow == NULL)
4899
23.4k
        g.HoverWindowUnlockedStationaryId = 0;
4900
4901
    // Update hover delay for IsItemHovered() with delays and tooltips
4902
25.7k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4903
25.7k
    if (g.HoverItemDelayId != 0)
4904
0
    {
4905
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4906
0
        g.HoverItemDelayClearTimer = 0.0f;
4907
0
        g.HoverItemDelayId = 0;
4908
0
    }
4909
25.7k
    else if (g.HoverItemDelayTimer > 0.0f)
4910
0
    {
4911
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4912
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4913
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4914
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4915
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4916
0
    }
4917
4918
    // Drag and drop
4919
25.7k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4920
25.7k
    g.DragDropAcceptIdCurr = 0;
4921
25.7k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4922
25.7k
    g.DragDropWithinSource = false;
4923
25.7k
    g.DragDropWithinTarget = false;
4924
25.7k
    g.DragDropHoldJustPressedId = 0;
4925
4926
    // Close popups on focus lost (currently wip/opt-in)
4927
    //if (g.IO.AppFocusLost)
4928
    //    ClosePopupsExceptModals();
4929
4930
    // Update keyboard input state
4931
25.7k
    UpdateKeyboardInputs();
4932
4933
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4934
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4935
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4936
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4937
4938
    // Update gamepad/keyboard navigation
4939
25.7k
    NavUpdate();
4940
4941
    // Update mouse input state
4942
25.7k
    UpdateMouseInputs();
4943
4944
    // Undocking
4945
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4946
25.7k
    DockContextNewFrameUpdateUndocking(&g);
4947
4948
    // Find hovered window
4949
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4950
25.7k
    UpdateHoveredWindowAndCaptureFlags();
4951
4952
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4953
25.7k
    UpdateMouseMovingWindowNewFrame();
4954
4955
    // Background darkening/whitening
4956
25.7k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4957
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4958
25.7k
    else
4959
25.7k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4960
4961
25.7k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4962
25.7k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4963
4964
    // Platform IME data: reset for the frame
4965
25.7k
    g.PlatformImeDataPrev = g.PlatformImeData;
4966
25.7k
    g.PlatformImeData.WantVisible = false;
4967
4968
    // Mouse wheel scrolling, scale
4969
25.7k
    UpdateMouseWheel();
4970
4971
    // Mark all windows as not visible and compact unused memory.
4972
25.7k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4973
25.7k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4974
25.7k
    for (ImGuiWindow* window : g.Windows)
4975
77.3k
    {
4976
77.3k
        window->WasActive = window->Active;
4977
77.3k
        window->Active = false;
4978
77.3k
        window->WriteAccessed = false;
4979
77.3k
        window->BeginCountPreviousFrame = window->BeginCount;
4980
77.3k
        window->BeginCount = 0;
4981
4982
        // Garbage collect transient buffers of recently unused windows
4983
77.3k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4984
0
            GcCompactTransientWindowBuffers(window);
4985
77.3k
    }
4986
4987
    // Garbage collect transient buffers of recently unused tables
4988
25.7k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4989
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4990
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4991
25.7k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
4992
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
4993
0
            TableGcCompactTransientBuffers(&table_temp_data);
4994
25.7k
    if (g.GcCompactAll)
4995
0
        GcCompactTransientMiscBuffers();
4996
25.7k
    g.GcCompactAll = false;
4997
4998
    // Closing the focused window restore focus to the first active root window in descending z-order
4999
25.7k
    if (g.NavWindow && !g.NavWindow->WasActive)
5000
0
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5001
5002
    // No window should be open at the beginning of the frame.
5003
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5004
25.7k
    g.CurrentWindowStack.resize(0);
5005
25.7k
    g.BeginPopupStack.resize(0);
5006
25.7k
    g.ItemFlagsStack.resize(0);
5007
25.7k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
5008
25.7k
    g.GroupStack.resize(0);
5009
5010
    // Docking
5011
25.7k
    DockContextNewFrameUpdateDocking(&g);
5012
5013
    // [DEBUG] Update debug features
5014
25.7k
    UpdateDebugToolItemPicker();
5015
25.7k
    UpdateDebugToolStackQueries();
5016
25.7k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5017
0
        g.DebugLocateId = 0;
5018
25.7k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
5019
0
    {
5020
0
        DebugLog("(Auto-disabled ImGuiDebugLogFlags_EventClipper to avoid spamming)\n");
5021
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
5022
0
    }
5023
5024
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5025
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5026
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5027
25.7k
    g.WithinFrameScopeWithImplicitWindow = true;
5028
25.7k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5029
25.7k
    Begin("Debug##Default");
5030
25.7k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5031
5032
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5033
    // allowing to validate correct Begin/End behavior in user code.
5034
25.7k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5035
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5036
25.7k
    else
5037
25.7k
        g.DebugBeginReturnValueCullDepth = -1;
5038
5039
25.7k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5040
25.7k
}
5041
5042
// FIXME: Add a more explicit sort order in the window structure.
5043
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5044
0
{
5045
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5046
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5047
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5048
0
        return d;
5049
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5050
0
        return d;
5051
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5052
0
}
5053
5054
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5055
77.3k
{
5056
77.3k
    out_sorted_windows->push_back(window);
5057
77.3k
    if (window->Active)
5058
51.5k
    {
5059
51.5k
        int count = window->DC.ChildWindows.Size;
5060
51.5k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5061
77.3k
        for (int i = 0; i < count; i++)
5062
25.7k
        {
5063
25.7k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5064
25.7k
            if (child->Active)
5065
25.7k
                AddWindowToSortBuffer(out_sorted_windows, child);
5066
25.7k
        }
5067
51.5k
    }
5068
77.3k
}
5069
5070
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5071
51.5k
{
5072
51.5k
    ImGuiContext& g = *GImGui;
5073
51.5k
    ImGuiViewportP* viewport = window->Viewport;
5074
51.5k
    IM_ASSERT(viewport != NULL);
5075
51.5k
    g.IO.MetricsRenderWindows++;
5076
51.5k
    if (window->DrawList->_Splitter._Count > 1)
5077
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5078
51.5k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5079
51.5k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5080
25.7k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5081
25.7k
            AddWindowToDrawData(child, layer);
5082
51.5k
}
5083
5084
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5085
25.7k
{
5086
25.7k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5087
25.7k
}
5088
5089
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5090
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5091
25.7k
{
5092
25.7k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5093
25.7k
}
5094
5095
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5096
25.7k
{
5097
25.7k
    int n = builder->Layers[0]->Size;
5098
25.7k
    int full_size = n;
5099
51.5k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5100
25.7k
        full_size += builder->Layers[i]->Size;
5101
25.7k
    builder->Layers[0]->resize(full_size);
5102
51.5k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5103
25.7k
    {
5104
25.7k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5105
25.7k
        if (layer->empty())
5106
25.7k
            continue;
5107
0
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5108
0
        n += layer->Size;
5109
0
        layer->resize(0);
5110
0
    }
5111
25.7k
}
5112
5113
static void InitViewportDrawData(ImGuiViewportP* viewport)
5114
25.7k
{
5115
25.7k
    ImGuiIO& io = ImGui::GetIO();
5116
25.7k
    ImDrawData* draw_data = &viewport->DrawDataP;
5117
5118
25.7k
    viewport->DrawData = draw_data; // Make publicly accessible
5119
25.7k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5120
25.7k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5121
25.7k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5122
25.7k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5123
5124
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5125
    // and to allow applications/backends to easily skip rendering.
5126
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5127
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5128
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5129
25.7k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5130
5131
25.7k
    draw_data->Valid = true;
5132
25.7k
    draw_data->CmdListsCount = 0;
5133
25.7k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5134
25.7k
    draw_data->DisplayPos = viewport->Pos;
5135
25.7k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5136
25.7k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5137
25.7k
    draw_data->OwnerViewport = viewport;
5138
25.7k
}
5139
5140
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5141
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5142
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5143
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5144
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5145
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5146
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5147
154k
{
5148
154k
    ImGuiWindow* window = GetCurrentWindow();
5149
154k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5150
154k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5151
154k
}
5152
5153
void ImGui::PopClipRect()
5154
77.3k
{
5155
77.3k
    ImGuiWindow* window = GetCurrentWindow();
5156
77.3k
    window->DrawList->PopClipRect();
5157
77.3k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5158
77.3k
}
5159
5160
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5161
0
{
5162
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5163
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5164
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5165
0
    return window;
5166
0
}
5167
5168
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5169
0
{
5170
0
    if ((col & IM_COL32_A_MASK) == 0)
5171
0
        return;
5172
5173
0
    ImGuiViewportP* viewport = window->Viewport;
5174
0
    ImRect viewport_rect = viewport->GetMainRect();
5175
5176
    // Draw behind window by moving the draw command at the FRONT of the draw list
5177
0
    {
5178
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5179
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5180
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5181
0
        draw_list->ChannelsMerge();
5182
0
        if (draw_list->CmdBuffer.Size == 0)
5183
0
            draw_list->AddDrawCmd();
5184
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5185
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5186
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5187
0
        IM_ASSERT(cmd.ElemCount == 6);
5188
0
        draw_list->CmdBuffer.pop_back();
5189
0
        draw_list->CmdBuffer.push_front(cmd);
5190
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5191
0
        draw_list->PopClipRect();
5192
0
    }
5193
5194
    // Draw over sibling docking nodes in a same docking tree
5195
0
    if (window->RootWindow->DockIsActive)
5196
0
    {
5197
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5198
0
        draw_list->ChannelsMerge();
5199
0
        if (draw_list->CmdBuffer.Size == 0)
5200
0
            draw_list->AddDrawCmd();
5201
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5202
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5203
0
        draw_list->PopClipRect();
5204
0
    }
5205
0
}
5206
5207
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5208
0
{
5209
0
    ImGuiContext& g = *GImGui;
5210
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5211
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5212
0
    {
5213
0
        ImGuiWindow* window = g.Windows[i];
5214
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5215
0
            continue;
5216
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5217
0
            break;
5218
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5219
0
            bottom_most_visible_window = window;
5220
0
    }
5221
0
    return bottom_most_visible_window;
5222
0
}
5223
5224
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5225
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5226
static void ImGui::RenderDimmedBackgrounds()
5227
25.7k
{
5228
25.7k
    ImGuiContext& g = *GImGui;
5229
25.7k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5230
25.7k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5231
25.7k
        return;
5232
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5233
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5234
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5235
0
        return;
5236
5237
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5238
0
    if (dim_bg_for_modal)
5239
0
    {
5240
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5241
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5242
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5243
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5244
0
    }
5245
0
    else if (dim_bg_for_window_list)
5246
0
    {
5247
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5248
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5249
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5250
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5251
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5252
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5253
5254
        // Draw border around CTRL+Tab target window
5255
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5256
0
        ImGuiViewport* viewport = window->Viewport;
5257
0
        float distance = g.FontSize;
5258
0
        ImRect bb = window->Rect();
5259
0
        bb.Expand(distance);
5260
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5261
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5262
0
        window->DrawList->ChannelsMerge();
5263
0
        if (window->DrawList->CmdBuffer.Size == 0)
5264
0
            window->DrawList->AddDrawCmd();
5265
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5266
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5267
0
        window->DrawList->PopClipRect();
5268
0
    }
5269
5270
    // Draw dimming background on _other_ viewports than the ones our windows are in
5271
0
    for (ImGuiViewportP* viewport : g.Viewports)
5272
0
    {
5273
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5274
0
            continue;
5275
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5276
0
            continue;
5277
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5278
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5279
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5280
0
    }
5281
0
}
5282
5283
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5284
void ImGui::EndFrame()
5285
51.5k
{
5286
51.5k
    ImGuiContext& g = *GImGui;
5287
51.5k
    IM_ASSERT(g.Initialized);
5288
5289
    // Don't process EndFrame() multiple times.
5290
51.5k
    if (g.FrameCountEnded == g.FrameCount)
5291
25.7k
        return;
5292
25.7k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5293
5294
25.7k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5295
5296
25.7k
    ErrorCheckEndFrameSanityChecks();
5297
5298
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5299
25.7k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5300
25.7k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5301
0
    {
5302
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5303
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5304
0
        if (viewport == NULL)
5305
0
            viewport = GetMainViewport();
5306
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5307
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5308
        {
5309
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5310
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5311
            viewport->PlatformHandleRaw = NULL;
5312
        }
5313
        else
5314
#endif
5315
0
        {
5316
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5317
0
        }
5318
0
    }
5319
5320
    // Hide implicit/fallback "Debug" window if it hasn't been used
5321
25.7k
    g.WithinFrameScopeWithImplicitWindow = false;
5322
25.7k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5323
25.7k
        g.CurrentWindow->Active = false;
5324
25.7k
    End();
5325
5326
    // Update navigation: CTRL+Tab, wrap-around requests
5327
25.7k
    NavEndFrame();
5328
5329
    // Update docking
5330
25.7k
    DockContextEndFrame(&g);
5331
5332
25.7k
    SetCurrentViewport(NULL, NULL);
5333
5334
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5335
25.7k
    if (g.DragDropActive)
5336
0
    {
5337
0
        bool is_delivered = g.DragDropPayload.Delivery;
5338
0
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5339
0
        if (is_delivered || is_elapsed)
5340
0
            ClearDragDrop();
5341
0
    }
5342
5343
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5344
25.7k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5345
0
    {
5346
0
        g.DragDropWithinSource = true;
5347
0
        SetTooltip("...");
5348
0
        g.DragDropWithinSource = false;
5349
0
    }
5350
5351
    // End frame
5352
25.7k
    g.WithinFrameScope = false;
5353
25.7k
    g.FrameCountEnded = g.FrameCount;
5354
5355
    // Initiate moving window + handle left-click and right-click focus
5356
25.7k
    UpdateMouseMovingWindowEndFrame();
5357
5358
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5359
25.7k
    UpdateViewportsEndFrame();
5360
5361
    // Sort the window list so that all child windows are after their parent
5362
    // We cannot do that on FocusWindow() because children may not exist yet
5363
25.7k
    g.WindowsTempSortBuffer.resize(0);
5364
25.7k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5365
25.7k
    for (ImGuiWindow* window : g.Windows)
5366
77.3k
    {
5367
77.3k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5368
25.7k
            continue;
5369
51.5k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5370
51.5k
    }
5371
5372
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5373
25.7k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5374
25.7k
    g.Windows.swap(g.WindowsTempSortBuffer);
5375
25.7k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5376
5377
    // Unlock font atlas
5378
25.7k
    g.IO.Fonts->Locked = false;
5379
5380
    // Clear Input data for next frame
5381
25.7k
    g.IO.MousePosPrev = g.IO.MousePos;
5382
25.7k
    g.IO.AppFocusLost = false;
5383
25.7k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5384
25.7k
    g.IO.InputQueueCharacters.resize(0);
5385
5386
25.7k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5387
25.7k
}
5388
5389
// Prepare the data for rendering so you can call GetDrawData()
5390
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5391
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5392
void ImGui::Render()
5393
25.7k
{
5394
25.7k
    ImGuiContext& g = *GImGui;
5395
25.7k
    IM_ASSERT(g.Initialized);
5396
5397
25.7k
    if (g.FrameCountEnded != g.FrameCount)
5398
25.7k
        EndFrame();
5399
25.7k
    if (g.FrameCountRendered == g.FrameCount)
5400
0
        return;
5401
25.7k
    g.FrameCountRendered = g.FrameCount;
5402
5403
25.7k
    g.IO.MetricsRenderWindows = 0;
5404
25.7k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5405
5406
    // Add background ImDrawList (for each active viewport)
5407
25.7k
    for (ImGuiViewportP* viewport : g.Viewports)
5408
25.7k
    {
5409
25.7k
        InitViewportDrawData(viewport);
5410
25.7k
        if (viewport->BgFgDrawLists[0] != NULL)
5411
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5412
25.7k
    }
5413
5414
    // Draw modal/window whitening backgrounds
5415
25.7k
    RenderDimmedBackgrounds();
5416
5417
    // Add ImDrawList to render
5418
25.7k
    ImGuiWindow* windows_to_render_top_most[2];
5419
25.7k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5420
25.7k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5421
25.7k
    for (ImGuiWindow* window : g.Windows)
5422
77.3k
    {
5423
77.3k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5424
77.3k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5425
25.7k
            AddRootWindowToDrawData(window);
5426
77.3k
    }
5427
77.3k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5428
51.5k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5429
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5430
5431
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5432
25.7k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5433
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5434
5435
    // Setup ImDrawData structures for end-user
5436
25.7k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5437
25.7k
    for (ImGuiViewportP* viewport : g.Viewports)
5438
25.7k
    {
5439
25.7k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5440
5441
        // Add foreground ImDrawList (for each active viewport)
5442
25.7k
        if (viewport->BgFgDrawLists[1] != NULL)
5443
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5444
5445
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5446
25.7k
        ImDrawData* draw_data = &viewport->DrawDataP;
5447
25.7k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5448
25.7k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5449
50.4k
            draw_list->_PopUnusedDrawCmd();
5450
5451
25.7k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5452
25.7k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5453
25.7k
    }
5454
5455
25.7k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5456
25.7k
}
5457
5458
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5459
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5460
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5461
51.5k
{
5462
51.5k
    ImGuiContext& g = *GImGui;
5463
5464
51.5k
    const char* text_display_end;
5465
51.5k
    if (hide_text_after_double_hash)
5466
51.5k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5467
0
    else
5468
0
        text_display_end = text_end;
5469
5470
51.5k
    ImFont* font = g.Font;
5471
51.5k
    const float font_size = g.FontSize;
5472
51.5k
    if (text == text_display_end)
5473
0
        return ImVec2(0.0f, font_size);
5474
51.5k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5475
5476
    // Round
5477
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5478
    // FIXME: Investigate using ceilf or e.g.
5479
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5480
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5481
51.5k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5482
5483
51.5k
    return text_size;
5484
51.5k
}
5485
5486
// Find window given position, search front-to-back
5487
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5488
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5489
// called, aka before the next Begin(). Moving window isn't affected.
5490
static void FindHoveredWindow()
5491
25.7k
{
5492
25.7k
    ImGuiContext& g = *GImGui;
5493
5494
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5495
25.7k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5496
25.7k
    if (g.MovingWindow)
5497
0
        g.MovingWindow->Viewport = g.MouseViewport;
5498
5499
25.7k
    ImGuiWindow* hovered_window = NULL;
5500
25.7k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5501
25.7k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5502
0
        hovered_window = g.MovingWindow;
5503
5504
25.7k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5505
25.7k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5506
98.4k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5507
75.0k
    {
5508
75.0k
        ImGuiWindow* window = g.Windows[i];
5509
75.0k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5510
75.0k
        if (!window->Active || window->Hidden)
5511
23.4k
            continue;
5512
51.5k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5513
0
            continue;
5514
51.5k
        IM_ASSERT(window->Viewport);
5515
51.5k
        if (window->Viewport != g.MouseViewport)
5516
0
            continue;
5517
5518
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5519
51.5k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5520
51.5k
        if (!window->OuterRectClipped.ContainsWithPad(g.IO.MousePos, hit_padding))
5521
49.2k
            continue;
5522
5523
        // Support for one rectangular hole in any given window
5524
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5525
2.30k
        if (window->HitTestHoleSize.x != 0)
5526
0
        {
5527
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5528
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5529
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5530
0
                continue;
5531
0
        }
5532
5533
2.30k
        if (hovered_window == NULL)
5534
2.30k
            hovered_window = window;
5535
2.30k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5536
2.30k
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5537
2.30k
            hovered_window_ignoring_moving_window = window;
5538
2.30k
        if (hovered_window && hovered_window_ignoring_moving_window)
5539
2.30k
            break;
5540
2.30k
    }
5541
5542
25.7k
    g.HoveredWindow = hovered_window;
5543
25.7k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5544
5545
25.7k
    if (g.MovingWindow)
5546
0
        g.MovingWindow->Viewport = moving_window_viewport;
5547
25.7k
}
5548
5549
bool ImGui::IsItemActive()
5550
51.5k
{
5551
51.5k
    ImGuiContext& g = *GImGui;
5552
51.5k
    if (g.ActiveId)
5553
296
        return g.ActiveId == g.LastItemData.ID;
5554
51.2k
    return false;
5555
51.5k
}
5556
5557
bool ImGui::IsItemActivated()
5558
0
{
5559
0
    ImGuiContext& g = *GImGui;
5560
0
    if (g.ActiveId)
5561
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5562
0
            return true;
5563
0
    return false;
5564
0
}
5565
5566
bool ImGui::IsItemDeactivated()
5567
0
{
5568
0
    ImGuiContext& g = *GImGui;
5569
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5570
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5571
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5572
0
}
5573
5574
bool ImGui::IsItemDeactivatedAfterEdit()
5575
0
{
5576
0
    ImGuiContext& g = *GImGui;
5577
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5578
0
}
5579
5580
// == GetItemID() == GetFocusID()
5581
bool ImGui::IsItemFocused()
5582
0
{
5583
0
    ImGuiContext& g = *GImGui;
5584
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5585
0
        return false;
5586
5587
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5588
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5589
0
    ImGuiWindow* window = g.CurrentWindow;
5590
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5591
0
        return false;
5592
5593
0
    return true;
5594
0
}
5595
5596
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5597
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5598
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5599
0
{
5600
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5601
0
}
5602
5603
bool ImGui::IsItemToggledOpen()
5604
0
{
5605
0
    ImGuiContext& g = *GImGui;
5606
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5607
0
}
5608
5609
bool ImGui::IsItemToggledSelection()
5610
0
{
5611
0
    ImGuiContext& g = *GImGui;
5612
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5613
0
}
5614
5615
bool ImGui::IsAnyItemHovered()
5616
0
{
5617
0
    ImGuiContext& g = *GImGui;
5618
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5619
0
}
5620
5621
bool ImGui::IsAnyItemActive()
5622
0
{
5623
0
    ImGuiContext& g = *GImGui;
5624
0
    return g.ActiveId != 0;
5625
0
}
5626
5627
bool ImGui::IsAnyItemFocused()
5628
0
{
5629
0
    ImGuiContext& g = *GImGui;
5630
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5631
0
}
5632
5633
bool ImGui::IsItemVisible()
5634
0
{
5635
0
    ImGuiContext& g = *GImGui;
5636
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5637
0
}
5638
5639
bool ImGui::IsItemEdited()
5640
0
{
5641
0
    ImGuiContext& g = *GImGui;
5642
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5643
0
}
5644
5645
// Allow next item to be overlapped by subsequent items.
5646
// This works by requiring HoveredId to match for two subsequent frames,
5647
// so if a following items overwrite it our interactions will naturally be disabled.
5648
void ImGui::SetNextItemAllowOverlap()
5649
0
{
5650
0
    ImGuiContext& g = *GImGui;
5651
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5652
0
}
5653
5654
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5655
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5656
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5657
void ImGui::SetItemAllowOverlap()
5658
{
5659
    ImGuiContext& g = *GImGui;
5660
    ImGuiID id = g.LastItemData.ID;
5661
    if (g.HoveredId == id)
5662
        g.HoveredIdAllowOverlap = true;
5663
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5664
        g.ActiveIdAllowOverlap = true;
5665
}
5666
#endif
5667
5668
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5669
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5670
0
{
5671
0
    ImGuiContext& g = *GImGui;
5672
0
    IM_ASSERT(g.ActiveId != 0);
5673
0
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5674
0
    g.ActiveIdUsingAllKeyboardKeys = true;
5675
0
    NavMoveRequestCancel();
5676
0
}
5677
5678
ImGuiID ImGui::GetItemID()
5679
0
{
5680
0
    ImGuiContext& g = *GImGui;
5681
0
    return g.LastItemData.ID;
5682
0
}
5683
5684
ImVec2 ImGui::GetItemRectMin()
5685
0
{
5686
0
    ImGuiContext& g = *GImGui;
5687
0
    return g.LastItemData.Rect.Min;
5688
0
}
5689
5690
ImVec2 ImGui::GetItemRectMax()
5691
0
{
5692
0
    ImGuiContext& g = *GImGui;
5693
0
    return g.LastItemData.Rect.Max;
5694
0
}
5695
5696
ImVec2 ImGui::GetItemRectSize()
5697
0
{
5698
0
    ImGuiContext& g = *GImGui;
5699
0
    return g.LastItemData.Rect.GetSize();
5700
0
}
5701
5702
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5703
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'.
5704
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5705
25.7k
{
5706
25.7k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5707
25.7k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5708
25.7k
}
5709
5710
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5711
0
{
5712
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5713
0
}
5714
5715
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5716
25.7k
{
5717
25.7k
    ImGuiContext& g = *GImGui;
5718
25.7k
    ImGuiWindow* parent_window = g.CurrentWindow;
5719
25.7k
    IM_ASSERT(id != 0);
5720
5721
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5722
25.7k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle;
5723
25.7k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5724
25.7k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5725
25.7k
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5726
25.7k
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5727
0
    {
5728
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5729
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5730
0
    }
5731
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5732
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5733
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5734
#endif
5735
25.7k
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5736
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5737
25.7k
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5738
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5739
5740
    // Set window flags
5741
25.7k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5742
25.7k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5743
25.7k
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5744
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5745
25.7k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5746
25.7k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5747
5748
    // Special framed style
5749
25.7k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5750
0
    {
5751
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5752
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5753
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5754
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5755
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5756
0
        window_flags |= ImGuiWindowFlags_NoMove;
5757
0
    }
5758
5759
    // Forward child flags
5760
25.7k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5761
25.7k
    g.NextWindowData.ChildFlags = child_flags;
5762
5763
    // Forward size
5764
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5765
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5766
25.7k
    const ImVec2 size_avail = GetContentRegionAvail();
5767
25.7k
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5768
25.7k
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5769
25.7k
    SetNextWindowSize(size);
5770
5771
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5772
25.7k
    const char* temp_window_name;
5773
25.7k
    if (name && parent_window->IDStack.back() == parent_window->ID)
5774
25.7k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5775
0
    else if (name)
5776
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5777
0
    else
5778
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5779
5780
    // Set style
5781
25.7k
    const float backup_border_size = g.Style.ChildBorderSize;
5782
25.7k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5783
18.0k
        g.Style.ChildBorderSize = 0.0f;
5784
5785
    // Begin into window
5786
25.7k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5787
5788
    // Restore style
5789
25.7k
    g.Style.ChildBorderSize = backup_border_size;
5790
25.7k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5791
0
    {
5792
0
        PopStyleVar(3);
5793
0
        PopStyleColor();
5794
0
    }
5795
5796
25.7k
    ImGuiWindow* child_window = g.CurrentWindow;
5797
25.7k
    child_window->ChildId = id;
5798
5799
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5800
    // While this is not really documented/defined, it seems that the expected thing to do.
5801
25.7k
    if (child_window->BeginCount == 1)
5802
25.7k
        parent_window->DC.CursorPos = child_window->Pos;
5803
5804
    // Process navigation-in immediately so NavInit can run on first frame
5805
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5806
25.7k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5807
25.7k
    if (g.ActiveId == temp_id_for_activation)
5808
0
        ClearActiveID();
5809
25.7k
    if (g.NavActivateId == id && !(window_flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5810
0
    {
5811
0
        FocusWindow(child_window);
5812
0
        NavInitWindow(child_window, false);
5813
0
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5814
0
        g.ActiveIdSource = g.NavInputSource;
5815
0
    }
5816
25.7k
    return ret;
5817
25.7k
}
5818
5819
void ImGui::EndChild()
5820
25.7k
{
5821
25.7k
    ImGuiContext& g = *GImGui;
5822
25.7k
    ImGuiWindow* child_window = g.CurrentWindow;
5823
5824
25.7k
    IM_ASSERT(g.WithinEndChild == false);
5825
25.7k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5826
5827
25.7k
    g.WithinEndChild = true;
5828
25.7k
    ImVec2 child_size = child_window->Size;
5829
25.7k
    End();
5830
25.7k
    if (child_window->BeginCount == 1)
5831
25.7k
    {
5832
25.7k
        ImGuiWindow* parent_window = g.CurrentWindow;
5833
25.7k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5834
25.7k
        ItemSize(child_size);
5835
25.7k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !(child_window->Flags & ImGuiWindowFlags_NavFlattened))
5836
24.6k
        {
5837
24.6k
            ItemAdd(bb, child_window->ChildId);
5838
24.6k
            RenderNavHighlight(bb, child_window->ChildId);
5839
5840
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5841
24.6k
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5842
22.4k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5843
24.6k
        }
5844
1.09k
        else
5845
1.09k
        {
5846
            // Not navigable into
5847
1.09k
            ItemAdd(bb, 0);
5848
5849
            // But when flattened we directly reach items, adjust active layer mask accordingly
5850
1.09k
            if (child_window->Flags & ImGuiWindowFlags_NavFlattened)
5851
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5852
1.09k
        }
5853
25.7k
        if (g.HoveredWindow == child_window)
5854
0
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5855
25.7k
    }
5856
25.7k
    g.WithinEndChild = false;
5857
25.7k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5858
25.7k
}
5859
5860
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5861
6
{
5862
6
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5863
6
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5864
6
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5865
6
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5866
6
}
5867
5868
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5869
77.3k
{
5870
77.3k
    ImGuiContext& g = *GImGui;
5871
77.3k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5872
77.3k
}
5873
5874
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5875
77.3k
{
5876
77.3k
    ImGuiID id = ImHashStr(name);
5877
77.3k
    return FindWindowByID(id);
5878
77.3k
}
5879
5880
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5881
0
{
5882
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5883
0
    window->ViewportPos = main_viewport->Pos;
5884
0
    if (settings->ViewportId)
5885
0
    {
5886
0
        window->ViewportId = settings->ViewportId;
5887
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5888
0
    }
5889
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5890
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5891
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
5892
0
    window->Collapsed = settings->Collapsed;
5893
0
    window->DockId = settings->DockId;
5894
0
    window->DockOrder = settings->DockOrder;
5895
0
}
5896
5897
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5898
77.3k
{
5899
77.3k
    ImGuiContext& g = *GImGui;
5900
5901
77.3k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5902
77.3k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5903
77.3k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5904
2
    {
5905
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5906
2
        g.WindowsFocusOrder.push_back(window);
5907
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5908
2
    }
5909
77.3k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5910
0
    {
5911
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5912
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5913
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5914
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5915
0
        window->FocusOrder = -1;
5916
0
    }
5917
77.3k
    window->IsExplicitChild = new_is_explicit_child;
5918
77.3k
}
5919
5920
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5921
3
{
5922
    // Initial window state with e.g. default/arbitrary window position
5923
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5924
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5925
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5926
3
    window->Size = window->SizeFull = ImVec2(0, 0);
5927
3
    window->ViewportPos = main_viewport->Pos;
5928
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5929
5930
3
    if (settings != NULL)
5931
0
    {
5932
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5933
0
        ApplyWindowSettings(window, settings);
5934
0
    }
5935
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5936
5937
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5938
0
    {
5939
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5940
0
        window->AutoFitOnlyGrows = false;
5941
0
    }
5942
3
    else
5943
3
    {
5944
3
        if (window->Size.x <= 0.0f)
5945
3
            window->AutoFitFramesX = 2;
5946
3
        if (window->Size.y <= 0.0f)
5947
3
            window->AutoFitFramesY = 2;
5948
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5949
3
    }
5950
3
}
5951
5952
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5953
3
{
5954
    // Create window the first time
5955
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5956
3
    ImGuiContext& g = *GImGui;
5957
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5958
3
    window->Flags = flags;
5959
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5960
5961
3
    ImGuiWindowSettings* settings = NULL;
5962
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5963
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5964
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5965
5966
3
    InitOrLoadWindowSettings(window, settings);
5967
5968
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5969
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5970
3
    else
5971
3
        g.Windows.push_back(window);
5972
5973
3
    return window;
5974
3
}
5975
5976
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5977
0
{
5978
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5979
0
}
5980
5981
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5982
154k
{
5983
154k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5984
154k
}
5985
5986
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
5987
231k
{
5988
    // Popups, menus and childs bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5989
231k
    ImGuiContext& g = *GImGui;
5990
231k
    ImVec2 size_min;
5991
231k
    if (window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_ChildWindow))
5992
77.3k
    {
5993
77.3k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
5994
77.3k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
5995
77.3k
    }
5996
154k
    else
5997
154k
    {
5998
154k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5999
154k
        size_min = g.Style.WindowMinSize;
6000
154k
        size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
6001
154k
    }
6002
231k
    return size_min;
6003
231k
}
6004
6005
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6006
154k
{
6007
154k
    ImGuiContext& g = *GImGui;
6008
154k
    ImVec2 new_size = size_desired;
6009
154k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6010
0
    {
6011
        // Using -1,-1 on either X/Y axis to preserve the current size.
6012
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6013
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6014
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6015
0
        if (g.NextWindowData.SizeCallback)
6016
0
        {
6017
0
            ImGuiSizeCallbackData data;
6018
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6019
0
            data.Pos = window->Pos;
6020
0
            data.CurrentSize = window->SizeFull;
6021
0
            data.DesiredSize = new_size;
6022
0
            g.NextWindowData.SizeCallback(&data);
6023
0
            new_size = data.DesiredSize;
6024
0
        }
6025
0
        new_size.x = IM_TRUNC(new_size.x);
6026
0
        new_size.y = IM_TRUNC(new_size.y);
6027
0
    }
6028
6029
    // Minimum size
6030
154k
    ImVec2 size_min = CalcWindowMinSize(window);
6031
154k
    return ImMax(new_size, size_min);
6032
154k
}
6033
6034
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6035
77.3k
{
6036
77.3k
    bool preserve_old_content_sizes = false;
6037
77.3k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6038
0
        preserve_old_content_sizes = true;
6039
77.3k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6040
0
        preserve_old_content_sizes = true;
6041
77.3k
    if (preserve_old_content_sizes)
6042
0
    {
6043
0
        *content_size_current = window->ContentSize;
6044
0
        *content_size_ideal = window->ContentSizeIdeal;
6045
0
        return;
6046
0
    }
6047
6048
77.3k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6049
77.3k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6050
77.3k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6051
77.3k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6052
77.3k
}
6053
6054
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6055
77.3k
{
6056
77.3k
    ImGuiContext& g = *GImGui;
6057
77.3k
    ImGuiStyle& style = g.Style;
6058
77.3k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6059
77.3k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6060
77.3k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6061
77.3k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6062
77.3k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6063
0
    {
6064
        // Tooltip always resize
6065
0
        return size_desired;
6066
0
    }
6067
77.3k
    else
6068
77.3k
    {
6069
        // Maximum window size is determined by the viewport size or monitor size
6070
77.3k
        ImVec2 size_min = CalcWindowMinSize(window);
6071
77.3k
        ImVec2 avail_size = window->Viewport->WorkSize;
6072
77.3k
        if (window->ViewportOwned)
6073
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
6074
77.3k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6075
77.3k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6076
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
6077
77.3k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
6078
6079
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6080
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6081
77.3k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6082
77.3k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6083
77.3k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6084
77.3k
        if (will_have_scrollbar_x)
6085
25.7k
            size_auto_fit.y += style.ScrollbarSize;
6086
77.3k
        if (will_have_scrollbar_y)
6087
181
            size_auto_fit.x += style.ScrollbarSize;
6088
77.3k
        return size_auto_fit;
6089
77.3k
    }
6090
77.3k
}
6091
6092
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6093
0
{
6094
0
    ImVec2 size_contents_current;
6095
0
    ImVec2 size_contents_ideal;
6096
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6097
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6098
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6099
0
    return size_final;
6100
0
}
6101
6102
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6103
77.3k
{
6104
77.3k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6105
0
        return ImGuiCol_PopupBg;
6106
77.3k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6107
25.7k
        return ImGuiCol_ChildBg;
6108
51.5k
    return ImGuiCol_WindowBg;
6109
77.3k
}
6110
6111
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6112
0
{
6113
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6114
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6115
0
    ImVec2 size_expected = pos_max - pos_min;
6116
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6117
0
    *out_pos = pos_min;
6118
0
    if (corner_norm.x == 0.0f)
6119
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6120
0
    if (corner_norm.y == 0.0f)
6121
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6122
0
    *out_size = size_constrained;
6123
0
}
6124
6125
// Data for resizing from resize grip / corner
6126
struct ImGuiResizeGripDef
6127
{
6128
    ImVec2  CornerPosN;
6129
    ImVec2  InnerDir;
6130
    int     AngleMin12, AngleMax12;
6131
};
6132
static const ImGuiResizeGripDef resize_grip_def[4] =
6133
{
6134
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6135
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6136
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6137
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6138
};
6139
6140
// Data for resizing from borders
6141
struct ImGuiResizeBorderDef
6142
{
6143
    ImVec2  InnerDir;               // Normal toward inside
6144
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6145
    float   OuterAngle;             // Angle toward outside
6146
};
6147
static const ImGuiResizeBorderDef resize_border_def[4] =
6148
{
6149
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6150
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6151
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6152
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6153
};
6154
6155
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6156
0
{
6157
0
    ImRect rect = window->Rect();
6158
0
    if (thickness == 0.0f)
6159
0
        rect.Max -= ImVec2(1, 1);
6160
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6161
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6162
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6163
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6164
0
    IM_ASSERT(0);
6165
0
    return ImRect();
6166
0
}
6167
6168
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6169
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6170
0
{
6171
0
    IM_ASSERT(n >= 0 && n < 4);
6172
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6173
0
    id = ImHashStr("#RESIZE", 0, id);
6174
0
    id = ImHashData(&n, sizeof(int), id);
6175
0
    return id;
6176
0
}
6177
6178
// Borders (Left, Right, Up, Down)
6179
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6180
0
{
6181
0
    IM_ASSERT(dir >= 0 && dir < 4);
6182
0
    int n = (int)dir + 4;
6183
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6184
0
    id = ImHashStr("#RESIZE", 0, id);
6185
0
    id = ImHashData(&n, sizeof(int), id);
6186
0
    return id;
6187
0
}
6188
6189
// Handle resize for: Resize Grips, Borders, Gamepad
6190
// Return true when using auto-fit (double-click on resize grip)
6191
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6192
77.3k
{
6193
77.3k
    ImGuiContext& g = *GImGui;
6194
77.3k
    ImGuiWindowFlags flags = window->Flags;
6195
6196
77.3k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6197
25.7k
        return false;
6198
51.5k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6199
25.7k
        return false;
6200
6201
25.7k
    int ret_auto_fit_mask = 0x00;
6202
25.7k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6203
25.7k
    const float grip_hover_inner_size = IM_TRUNC(grip_draw_size * 0.75f);
6204
25.7k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6205
6206
25.7k
    ImRect clamp_rect = visibility_rect;
6207
25.7k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6208
25.7k
    if (window_move_from_title_bar)
6209
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6210
6211
25.7k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6212
25.7k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6213
6214
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6215
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6216
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6217
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6218
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6219
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6220
25.7k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6221
25.7k
    if (clip_with_viewport_rect)
6222
25.7k
        window->ClipRect = window->Viewport->GetMainRect();
6223
6224
    // Resize grips and borders are on layer 1
6225
25.7k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6226
6227
    // Manual resize grips
6228
25.7k
    PushID("#RESIZE");
6229
51.5k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6230
25.7k
    {
6231
25.7k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6232
25.7k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6233
6234
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6235
25.7k
        bool hovered, held;
6236
25.7k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6237
25.7k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6238
25.7k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6239
25.7k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6240
25.7k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6241
25.7k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6242
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6243
25.7k
        if (hovered || held)
6244
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6245
6246
25.7k
        if (held && g.IO.MouseDoubleClicked[0])
6247
0
        {
6248
            // Auto-fit when double-clicking
6249
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6250
0
            ret_auto_fit_mask = 0x03; // Both axises
6251
0
            ClearActiveID();
6252
0
        }
6253
25.7k
        else if (held)
6254
0
        {
6255
            // Resize from any of the four corners
6256
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6257
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6258
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6259
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6260
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6261
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6262
0
        }
6263
6264
        // Only lower-left grip is visible before hovering/activating
6265
25.7k
        if (resize_grip_n == 0 || held || hovered)
6266
25.7k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6267
25.7k
    }
6268
6269
25.7k
    int resize_border_mask = 0x00;
6270
25.7k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6271
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6272
25.7k
    else
6273
25.7k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6274
128k
    for (int border_n = 0; border_n < 4; border_n++)
6275
103k
    {
6276
103k
        if ((resize_border_mask & (1 << border_n)) == 0)
6277
103k
            continue;
6278
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6279
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6280
6281
0
        bool hovered, held;
6282
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6283
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6284
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6285
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6286
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6287
0
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6288
0
            hovered = false;
6289
0
        if (hovered || held)
6290
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6291
0
        if (held && g.IO.MouseDoubleClicked[0])
6292
0
        {
6293
            // Double-clicking bottom or right border auto-fit on this axis
6294
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6295
0
            if (border_n == 1 || border_n == 3) // Right and bottom border
6296
0
            {
6297
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6298
0
                ret_auto_fit_mask |= (1 << axis);
6299
0
                hovered = held = false; // So border doesn't show highlighted at new position
6300
0
            }
6301
0
            ClearActiveID();
6302
0
        }
6303
0
        else if (held)
6304
0
        {
6305
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6306
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6307
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6308
0
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6309
0
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6310
0
            {
6311
0
                g.WindowResizeBorderExpectedRect = border_rect;
6312
0
                g.WindowResizeRelativeMode = false;
6313
0
            }
6314
0
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6315
0
                g.WindowResizeRelativeMode = true;
6316
6317
0
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6318
0
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6319
0
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6320
6321
            // Use absolute mode position
6322
0
            ImVec2 border_target = window->Pos;
6323
0
            border_target[axis] = border_target_abs_mode_for_axis;
6324
6325
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6326
0
            bool ignore_resize = false;
6327
0
            if (g.WindowResizeRelativeMode)
6328
0
            {
6329
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6330
0
                border_target[axis] = border_target_rel_mode_for_axis;
6331
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6332
0
                    ignore_resize = true;
6333
0
            }
6334
6335
            // Clamp, apply
6336
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6337
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6338
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6339
0
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6340
0
            {
6341
0
                if ((flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (flags & ImGuiWindowFlags_NoScrollbar))
6342
0
                    border_target.x = ImClamp(border_target.x, window->ParentWindow->InnerClipRect.Min.x, window->ParentWindow->InnerClipRect.Max.x);
6343
0
                if (flags & ImGuiWindowFlags_NoScrollbar)
6344
0
                    border_target.y = ImClamp(border_target.y, window->ParentWindow->InnerClipRect.Min.y, window->ParentWindow->InnerClipRect.Max.y);
6345
0
            }
6346
0
            if (!ignore_resize)
6347
0
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6348
0
        }
6349
0
        if (hovered)
6350
0
            *border_hovered = border_n;
6351
0
        if (held)
6352
0
            *border_held = border_n;
6353
0
    }
6354
25.7k
    PopID();
6355
6356
    // Restore nav layer
6357
25.7k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6358
6359
    // Navigation resize (keyboard/gamepad)
6360
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6361
    // Not even sure the callback works here.
6362
25.7k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6363
0
    {
6364
0
        ImVec2 nav_resize_dir;
6365
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6366
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6367
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6368
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6369
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6370
0
        {
6371
0
            const float NAV_RESIZE_SPEED = 600.0f;
6372
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6373
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6374
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6375
0
            g.NavWindowingToggleLayer = false;
6376
0
            g.NavDisableMouseHover = true;
6377
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6378
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6379
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6380
0
            {
6381
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6382
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6383
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6384
0
            }
6385
0
        }
6386
0
    }
6387
6388
    // Apply back modified position/size to window
6389
25.7k
    if (size_target.x != FLT_MAX)
6390
0
        window->Size.x = window->SizeFull.x = size_target.x;
6391
25.7k
    if (size_target.y != FLT_MAX)
6392
0
        window->Size.y = window->SizeFull.y = size_target.y;
6393
25.7k
    if (pos_target.x != FLT_MAX)
6394
0
        window->Pos.x = ImTrunc(pos_target.x);
6395
25.7k
    if (pos_target.y != FLT_MAX)
6396
0
        window->Pos.y = ImTrunc(pos_target.y);
6397
25.7k
    if (size_target.x != FLT_MAX || size_target.y != FLT_MAX || pos_target.x != FLT_MAX || pos_target.y != FLT_MAX)
6398
0
        MarkIniSettingsDirty(window);
6399
6400
    // Recalculate next expected border expected coordinates
6401
25.7k
    if (*border_held != -1)
6402
0
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6403
6404
25.7k
    return ret_auto_fit_mask;
6405
51.5k
}
6406
6407
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6408
51.5k
{
6409
51.5k
    ImGuiContext& g = *GImGui;
6410
51.5k
    ImVec2 size_for_clamping = window->Size;
6411
51.5k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6412
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6413
51.5k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6414
51.5k
}
6415
6416
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6417
77.3k
{
6418
77.3k
    ImGuiContext& g = *GImGui;
6419
77.3k
    float rounding = window->WindowRounding;
6420
77.3k
    float border_size = window->WindowBorderSize;
6421
77.3k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6422
59.2k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6423
6424
77.3k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6425
0
    {
6426
0
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6427
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6428
0
        const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6429
0
        const ImU32 border_col = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6430
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6431
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6432
0
        window->DrawList->PathStroke(border_col, 0, ImMax(2.0f, border_size)); // Thicker than usual
6433
0
    }
6434
77.3k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6435
0
    {
6436
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6437
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6438
0
    }
6439
77.3k
}
6440
6441
// Draw background and borders
6442
// Draw and handle scrollbars
6443
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6444
77.3k
{
6445
77.3k
    ImGuiContext& g = *GImGui;
6446
77.3k
    ImGuiStyle& style = g.Style;
6447
77.3k
    ImGuiWindowFlags flags = window->Flags;
6448
6449
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6450
77.3k
    IM_ASSERT(window->BeginCount == 0);
6451
77.3k
    window->SkipItems = false;
6452
6453
    // Draw window + handle manual resize
6454
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6455
77.3k
    const float window_rounding = window->WindowRounding;
6456
77.3k
    const float window_border_size = window->WindowBorderSize;
6457
77.3k
    if (window->Collapsed)
6458
0
    {
6459
        // Title bar only
6460
0
        const float backup_border_size = style.FrameBorderSize;
6461
0
        g.Style.FrameBorderSize = window->WindowBorderSize;
6462
0
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6463
0
        if (window->ViewportOwned)
6464
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6465
0
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6466
0
        g.Style.FrameBorderSize = backup_border_size;
6467
0
    }
6468
77.3k
    else
6469
77.3k
    {
6470
        // Window background
6471
77.3k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6472
77.3k
        {
6473
77.3k
            bool is_docking_transparent_payload = false;
6474
77.3k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6475
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6476
0
                    is_docking_transparent_payload = true;
6477
6478
77.3k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6479
77.3k
            if (window->ViewportOwned)
6480
0
            {
6481
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6482
0
                if (is_docking_transparent_payload)
6483
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6484
0
            }
6485
77.3k
            else
6486
77.3k
            {
6487
                // Adjust alpha. For docking
6488
77.3k
                bool override_alpha = false;
6489
77.3k
                float alpha = 1.0f;
6490
77.3k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6491
0
                {
6492
0
                    alpha = g.NextWindowData.BgAlphaVal;
6493
0
                    override_alpha = true;
6494
0
                }
6495
77.3k
                if (is_docking_transparent_payload)
6496
0
                {
6497
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6498
0
                    override_alpha = true;
6499
0
                }
6500
77.3k
                if (override_alpha)
6501
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6502
77.3k
            }
6503
6504
            // Render, for docked windows and host windows we ensure bg goes before decorations
6505
77.3k
            if (window->DockIsActive)
6506
0
                window->DockNode->LastBgColor = bg_col;
6507
77.3k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6508
77.3k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6509
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6510
77.3k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6511
77.3k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6512
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6513
77.3k
        }
6514
77.3k
        if (window->DockIsActive)
6515
0
            window->DockNode->IsBgDrawnThisFrame = true;
6516
6517
        // Title bar
6518
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6519
        // in order for their pos/size to be matching their undocking state.)
6520
77.3k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6521
51.5k
        {
6522
51.5k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6523
51.5k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6524
51.5k
        }
6525
6526
        // Menu bar
6527
77.3k
        if (flags & ImGuiWindowFlags_MenuBar)
6528
0
        {
6529
0
            ImRect menu_bar_rect = window->MenuBarRect();
6530
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6531
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6532
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6533
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6534
0
        }
6535
6536
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6537
77.3k
        ImGuiDockNode* node = window->DockNode;
6538
77.3k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6539
0
        {
6540
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6541
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6542
0
            ImVec2 p = node->Pos;
6543
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6544
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6545
0
            KeepAliveID(unhide_id);
6546
0
            bool hovered, held;
6547
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6548
0
                node->WantHiddenTabBarToggle = true;
6549
0
            else if (held && IsMouseDragging(0))
6550
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6551
6552
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6553
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6554
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6555
0
        }
6556
6557
        // Scrollbars
6558
77.3k
        if (window->ScrollbarX)
6559
25.7k
            Scrollbar(ImGuiAxis_X);
6560
77.3k
        if (window->ScrollbarY)
6561
26.3k
            Scrollbar(ImGuiAxis_Y);
6562
6563
        // Render resize grips (after their input handling so we don't have a frame of latency)
6564
77.3k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6565
51.5k
        {
6566
103k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6567
51.5k
            {
6568
51.5k
                const ImU32 col = resize_grip_col[resize_grip_n];
6569
51.5k
                if ((col & IM_COL32_A_MASK) == 0)
6570
25.7k
                    continue;
6571
25.7k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6572
25.7k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6573
25.7k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6574
25.7k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6575
25.7k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6576
25.7k
                window->DrawList->PathFillConvex(col);
6577
25.7k
            }
6578
51.5k
        }
6579
6580
        // Borders (for dock node host they will be rendered over after the tab bar)
6581
77.3k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6582
77.3k
            RenderWindowOuterBorders(window);
6583
77.3k
    }
6584
77.3k
}
6585
6586
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6587
// Render title text, collapse button, close button
6588
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6589
51.5k
{
6590
51.5k
    ImGuiContext& g = *GImGui;
6591
51.5k
    ImGuiStyle& style = g.Style;
6592
51.5k
    ImGuiWindowFlags flags = window->Flags;
6593
6594
51.5k
    const bool has_close_button = (p_open != NULL);
6595
51.5k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6596
6597
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6598
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6599
51.5k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6600
51.5k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6601
51.5k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6602
6603
    // Layout buttons
6604
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6605
51.5k
    float pad_l = style.FramePadding.x;
6606
51.5k
    float pad_r = style.FramePadding.x;
6607
51.5k
    float button_sz = g.FontSize;
6608
51.5k
    ImVec2 close_button_pos;
6609
51.5k
    ImVec2 collapse_button_pos;
6610
51.5k
    if (has_close_button)
6611
0
    {
6612
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6613
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6614
0
    }
6615
51.5k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6616
0
    {
6617
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6618
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6619
0
    }
6620
51.5k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6621
51.5k
    {
6622
51.5k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6623
51.5k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6624
51.5k
    }
6625
6626
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6627
51.5k
    if (has_collapse_button)
6628
51.5k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6629
0
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6630
6631
    // Close button
6632
51.5k
    if (has_close_button)
6633
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6634
0
            *p_open = false;
6635
6636
51.5k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6637
51.5k
    g.CurrentItemFlags = item_flags_backup;
6638
6639
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6640
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6641
51.5k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6642
51.5k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6643
6644
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6645
    // while uncentered title text will still reach edges correctly.
6646
51.5k
    if (pad_l > style.FramePadding.x)
6647
51.5k
        pad_l += g.Style.ItemInnerSpacing.x;
6648
51.5k
    if (pad_r > style.FramePadding.x)
6649
0
        pad_r += g.Style.ItemInnerSpacing.x;
6650
51.5k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6651
0
    {
6652
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6653
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6654
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6655
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6656
0
    }
6657
6658
51.5k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6659
51.5k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6660
51.5k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6661
0
    {
6662
0
        ImVec2 marker_pos;
6663
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6664
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6665
0
        if (marker_pos.x > layout_r.Min.x)
6666
0
        {
6667
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6668
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6669
0
        }
6670
0
    }
6671
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6672
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6673
51.5k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6674
51.5k
}
6675
6676
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6677
77.3k
{
6678
77.3k
    window->ParentWindow = parent_window;
6679
77.3k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6680
77.3k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6681
25.7k
    {
6682
25.7k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6683
25.7k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6684
25.7k
            window->RootWindow = parent_window->RootWindow;
6685
25.7k
    }
6686
77.3k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6687
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6688
77.3k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6689
25.7k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6690
77.3k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6691
0
    {
6692
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6693
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6694
0
    }
6695
77.3k
}
6696
6697
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6698
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6699
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6700
// - WindowA            // FindBlockingModal() returns Modal1
6701
//   - WindowB          //                  .. returns Modal1
6702
//   - Modal1           //                  .. returns Modal2
6703
//      - WindowC       //                  .. returns Modal2
6704
//          - WindowD   //                  .. returns Modal2
6705
//          - Modal2    //                  .. returns Modal2
6706
//            - WindowE //                  .. returns NULL
6707
// Notes:
6708
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6709
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6710
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6711
601
{
6712
601
    ImGuiContext& g = *GImGui;
6713
601
    if (g.OpenPopupStack.Size <= 0)
6714
601
        return NULL;
6715
6716
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6717
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6718
0
    {
6719
0
        ImGuiWindow* popup_window = popup_data.Window;
6720
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6721
0
            continue;
6722
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6723
0
            continue;
6724
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6725
0
            return popup_window;
6726
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6727
0
            continue;
6728
0
        return popup_window;                                        // Place window right below first block modal
6729
0
    }
6730
0
    return NULL;
6731
0
}
6732
6733
// Push a new Dear ImGui window to add widgets to.
6734
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6735
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6736
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6737
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6738
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6739
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6740
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6741
77.3k
{
6742
77.3k
    ImGuiContext& g = *GImGui;
6743
77.3k
    const ImGuiStyle& style = g.Style;
6744
77.3k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6745
77.3k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6746
77.3k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6747
6748
    // Find or create
6749
77.3k
    ImGuiWindow* window = FindWindowByName(name);
6750
77.3k
    const bool window_just_created = (window == NULL);
6751
77.3k
    if (window_just_created)
6752
3
        window = CreateNewWindow(name, flags);
6753
6754
    // Automatically disable manual moving/resizing when NoInputs is set
6755
77.3k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6756
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6757
6758
77.3k
    if (flags & ImGuiWindowFlags_NavFlattened)
6759
77.3k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6760
6761
77.3k
    const int current_frame = g.FrameCount;
6762
77.3k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6763
77.3k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6764
6765
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6766
77.3k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6767
77.3k
    if (flags & ImGuiWindowFlags_Popup)
6768
0
    {
6769
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6770
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6771
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6772
0
    }
6773
6774
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6775
77.3k
    const bool window_was_appearing = window->Appearing;
6776
77.3k
    if (first_begin_of_the_frame)
6777
77.3k
    {
6778
77.3k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6779
77.3k
        window->Appearing = window_just_activated_by_user;
6780
77.3k
        if (window->Appearing)
6781
3
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6782
77.3k
        window->FlagsPreviousFrame = window->Flags;
6783
77.3k
        window->Flags = (ImGuiWindowFlags)flags;
6784
77.3k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6785
77.3k
        window->LastFrameActive = current_frame;
6786
77.3k
        window->LastTimeActive = (float)g.Time;
6787
77.3k
        window->BeginOrderWithinParent = 0;
6788
77.3k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6789
77.3k
    }
6790
0
    else
6791
0
    {
6792
0
        flags = window->Flags;
6793
0
    }
6794
6795
    // Docking
6796
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6797
77.3k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6798
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6799
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6800
77.3k
    if (first_begin_of_the_frame)
6801
77.3k
    {
6802
77.3k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6803
77.3k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6804
77.3k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6805
77.3k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6806
77.3k
        if (has_dock_node || new_auto_dock_node)
6807
0
        {
6808
0
            BeginDocked(window, p_open);
6809
0
            flags = window->Flags;
6810
0
            if (window->DockIsActive)
6811
0
            {
6812
0
                IM_ASSERT(window->DockNode != NULL);
6813
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6814
0
            }
6815
6816
            // Amend the Appearing flag
6817
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6818
0
            {
6819
0
                window->Appearing = true;
6820
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6821
0
            }
6822
0
        }
6823
77.3k
        else
6824
77.3k
        {
6825
77.3k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6826
77.3k
        }
6827
77.3k
    }
6828
6829
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6830
77.3k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6831
77.3k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6832
77.3k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6833
6834
    // We allow window memory to be compacted so recreate the base stack when needed.
6835
77.3k
    if (window->IDStack.Size == 0)
6836
0
        window->IDStack.push_back(window->ID);
6837
6838
    // Add to stack
6839
77.3k
    g.CurrentWindow = window;
6840
77.3k
    ImGuiWindowStackData window_stack_data;
6841
77.3k
    window_stack_data.Window = window;
6842
77.3k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6843
77.3k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6844
77.3k
    g.CurrentWindowStack.push_back(window_stack_data);
6845
77.3k
    if (flags & ImGuiWindowFlags_ChildMenu)
6846
0
        g.BeginMenuCount++;
6847
6848
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6849
77.3k
    if (first_begin_of_the_frame)
6850
77.3k
    {
6851
77.3k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6852
77.3k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6853
77.3k
    }
6854
6855
    // Add to focus scope stack
6856
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6857
77.3k
    PushFocusScope(window->ID);
6858
77.3k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6859
77.3k
    g.CurrentWindow = NULL;
6860
6861
    // Add to popup stack
6862
77.3k
    if (flags & ImGuiWindowFlags_Popup)
6863
0
    {
6864
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6865
0
        popup_ref.Window = window;
6866
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6867
0
        g.BeginPopupStack.push_back(popup_ref);
6868
0
        window->PopupId = popup_ref.PopupId;
6869
0
    }
6870
6871
    // Process SetNextWindow***() calls
6872
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6873
77.3k
    bool window_pos_set_by_api = false;
6874
77.3k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6875
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6876
0
    {
6877
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6878
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6879
0
        {
6880
            // May be processed on the next frame if this is our first frame and we are measuring size
6881
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6882
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6883
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6884
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6885
0
        }
6886
0
        else
6887
0
        {
6888
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6889
0
        }
6890
0
    }
6891
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6892
51.5k
    {
6893
51.5k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6894
51.5k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6895
51.5k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
6896
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
6897
51.5k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
6898
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
6899
51.5k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6900
51.5k
    }
6901
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6902
0
    {
6903
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6904
0
        {
6905
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6906
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6907
0
        }
6908
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6909
0
        {
6910
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6911
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6912
0
        }
6913
0
    }
6914
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6915
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6916
77.3k
    else if (first_begin_of_the_frame)
6917
77.3k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6918
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6919
0
        window->WindowClass = g.NextWindowData.WindowClass;
6920
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6921
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6922
77.3k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6923
0
        FocusWindow(window);
6924
77.3k
    if (window->Appearing)
6925
3
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6926
6927
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6928
77.3k
    if (first_begin_of_the_frame)
6929
77.3k
    {
6930
        // Initialize
6931
77.3k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6932
77.3k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6933
77.3k
        window->Active = true;
6934
77.3k
        window->HasCloseButton = (p_open != NULL);
6935
77.3k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6936
77.3k
        window->IDStack.resize(1);
6937
77.3k
        window->DrawList->_ResetForNewFrame();
6938
77.3k
        window->DC.CurrentTableIdx = -1;
6939
77.3k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6940
0
        {
6941
0
            window->DrawList->ChannelsSplit(2);
6942
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6943
0
        }
6944
6945
        // Restore buffer capacity when woken from a compacted state, to avoid
6946
77.3k
        if (window->MemoryCompacted)
6947
0
            GcAwakeTransientWindowBuffers(window);
6948
6949
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6950
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6951
77.3k
        bool window_title_visible_elsewhere = false;
6952
77.3k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6953
0
            window_title_visible_elsewhere = true;
6954
77.3k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6955
0
            window_title_visible_elsewhere = true;
6956
77.3k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6957
0
        {
6958
0
            size_t buf_len = (size_t)window->NameBufLen;
6959
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6960
0
            window->NameBufLen = (int)buf_len;
6961
0
        }
6962
6963
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6964
6965
        // Update contents size from last frame for auto-fitting (or use explicit size)
6966
77.3k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6967
6968
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6969
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6970
        // it has a single usage before this code block and may be set below before it is finally checked.
6971
77.3k
        if (window->HiddenFramesCanSkipItems > 0)
6972
0
            window->HiddenFramesCanSkipItems--;
6973
77.3k
        if (window->HiddenFramesCannotSkipItems > 0)
6974
2
            window->HiddenFramesCannotSkipItems--;
6975
77.3k
        if (window->HiddenFramesForRenderOnly > 0)
6976
0
            window->HiddenFramesForRenderOnly--;
6977
6978
        // Hide new windows for one frame until they calculate their size
6979
77.3k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6980
1
            window->HiddenFramesCannotSkipItems = 1;
6981
6982
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6983
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6984
77.3k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6985
0
        {
6986
0
            window->HiddenFramesCannotSkipItems = 1;
6987
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6988
0
            {
6989
0
                if (!window_size_x_set_by_api)
6990
0
                    window->Size.x = window->SizeFull.x = 0.f;
6991
0
                if (!window_size_y_set_by_api)
6992
0
                    window->Size.y = window->SizeFull.y = 0.f;
6993
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6994
0
            }
6995
0
        }
6996
6997
        // SELECT VIEWPORT
6998
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6999
7000
77.3k
        WindowSelectViewport(window);
7001
77.3k
        SetCurrentViewport(window, window->Viewport);
7002
77.3k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7003
77.3k
        SetCurrentWindow(window);
7004
77.3k
        flags = window->Flags;
7005
7006
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7007
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7008
7009
77.3k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7010
25.7k
            window->WindowBorderSize = style.ChildBorderSize;
7011
51.5k
        else
7012
51.5k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7013
77.3k
        window->WindowPadding = style.WindowPadding;
7014
77.3k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7015
18.0k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7016
7017
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7018
77.3k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7019
77.3k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7020
7021
77.3k
        bool use_current_size_for_scrollbar_x = window_just_created;
7022
77.3k
        bool use_current_size_for_scrollbar_y = window_just_created;
7023
7024
        // Collapse window by double-clicking on title bar
7025
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7026
77.3k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7027
51.5k
        {
7028
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7029
51.5k
            ImRect title_bar_rect = window->TitleBarRect();
7030
51.5k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
7031
0
                window->WantCollapseToggle = true;
7032
51.5k
            if (window->WantCollapseToggle)
7033
0
            {
7034
0
                window->Collapsed = !window->Collapsed;
7035
0
                if (!window->Collapsed)
7036
0
                    use_current_size_for_scrollbar_y = true;
7037
0
                MarkIniSettingsDirty(window);
7038
0
            }
7039
51.5k
        }
7040
25.7k
        else
7041
25.7k
        {
7042
25.7k
            window->Collapsed = false;
7043
25.7k
        }
7044
77.3k
        window->WantCollapseToggle = false;
7045
7046
        // SIZE
7047
7048
        // Outer Decoration Sizes
7049
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
7050
77.3k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7051
77.3k
        window->DecoOuterSizeX1 = 0.0f;
7052
77.3k
        window->DecoOuterSizeX2 = 0.0f;
7053
77.3k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
7054
77.3k
        window->DecoOuterSizeY2 = 0.0f;
7055
77.3k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7056
7057
        // Calculate auto-fit size, handle automatic resize
7058
77.3k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7059
77.3k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7060
0
        {
7061
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7062
0
            if (!window_size_x_set_by_api)
7063
0
            {
7064
0
                window->SizeFull.x = size_auto_fit.x;
7065
0
                use_current_size_for_scrollbar_x = true;
7066
0
            }
7067
0
            if (!window_size_y_set_by_api)
7068
0
            {
7069
0
                window->SizeFull.y = size_auto_fit.y;
7070
0
                use_current_size_for_scrollbar_y = true;
7071
0
            }
7072
0
        }
7073
77.3k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7074
2
        {
7075
            // Auto-fit may only grow window during the first few frames
7076
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7077
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7078
2
            {
7079
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7080
2
                use_current_size_for_scrollbar_x = true;
7081
2
            }
7082
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7083
2
            {
7084
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7085
2
                use_current_size_for_scrollbar_y = true;
7086
2
            }
7087
2
            if (!window->Collapsed)
7088
2
                MarkIniSettingsDirty(window);
7089
2
        }
7090
7091
        // Apply minimum/maximum window size constraints and final size
7092
77.3k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7093
77.3k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7094
7095
        // POSITION
7096
7097
        // Popup latch its initial position, will position itself when it appears next frame
7098
77.3k
        if (window_just_activated_by_user)
7099
3
        {
7100
3
            window->AutoPosLastDirection = ImGuiDir_None;
7101
3
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7102
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7103
3
        }
7104
7105
        // Position child window
7106
77.3k
        if (flags & ImGuiWindowFlags_ChildWindow)
7107
25.7k
        {
7108
25.7k
            IM_ASSERT(parent_window && parent_window->Active);
7109
25.7k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7110
25.7k
            parent_window->DC.ChildWindows.push_back(window);
7111
25.7k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7112
25.7k
                window->Pos = parent_window->DC.CursorPos;
7113
25.7k
        }
7114
7115
77.3k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7116
77.3k
        if (window_pos_with_pivot)
7117
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7118
77.3k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7119
0
            window->Pos = FindBestWindowPosForPopup(window);
7120
77.3k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7121
0
            window->Pos = FindBestWindowPosForPopup(window);
7122
77.3k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7123
0
            window->Pos = FindBestWindowPosForPopup(window);
7124
7125
        // Late create viewport if we don't fit within our current host viewport.
7126
77.3k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7127
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7128
0
            {
7129
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7130
                //ImGuiViewport* old_viewport = window->Viewport;
7131
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7132
7133
                // FIXME-DPI
7134
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7135
0
                SetCurrentViewport(window, window->Viewport);
7136
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7137
0
                SetCurrentWindow(window);
7138
0
            }
7139
7140
77.3k
        if (window->ViewportOwned)
7141
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7142
7143
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7144
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7145
77.3k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7146
77.3k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7147
77.3k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7148
77.3k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7149
7150
        // Clamp position/size so window stays visible within its viewport or monitor
7151
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7152
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7153
77.3k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7154
51.5k
        {
7155
51.5k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7156
51.5k
            {
7157
51.5k
                ClampWindowPos(window, visibility_rect);
7158
51.5k
            }
7159
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7160
0
            {
7161
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7162
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7163
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
7164
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
7165
0
                ClampWindowPos(window, visibility_rect);
7166
0
            }
7167
51.5k
        }
7168
77.3k
        window->Pos = ImTrunc(window->Pos);
7169
7170
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7171
        // Large values tend to lead to variety of artifacts and are not recommended.
7172
77.3k
        if (window->ViewportOwned || window->DockIsActive)
7173
0
            window->WindowRounding = 0.0f;
7174
77.3k
        else
7175
77.3k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7176
7177
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7178
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7179
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7180
7181
        // Apply window focus (new and reactivated windows are moved to front)
7182
77.3k
        bool want_focus = false;
7183
77.3k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7184
3
        {
7185
3
            if (flags & ImGuiWindowFlags_Popup)
7186
0
                want_focus = true;
7187
3
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7188
2
                want_focus = true;
7189
3
        }
7190
7191
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7192
#ifdef IMGUI_ENABLE_TEST_ENGINE
7193
        if (g.TestEngineHookItems)
7194
        {
7195
            IM_ASSERT(window->IDStack.Size == 1);
7196
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7197
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7198
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7199
            window->IDStack.Size = 1;
7200
        }
7201
#endif
7202
7203
        // Decide if we are going to handle borders and resize grips
7204
77.3k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7205
7206
        // Handle manual resize: Resize Grips, Borders, Gamepad
7207
77.3k
        int border_hovered = -1, border_held = -1;
7208
77.3k
        ImU32 resize_grip_col[4] = {};
7209
77.3k
        const int resize_grip_count = (window->Flags & ImGuiWindowFlags_ChildWindow) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7210
77.3k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7211
77.3k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7212
77.3k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7213
0
            {
7214
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7215
0
                    use_current_size_for_scrollbar_x = true;
7216
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7217
0
                    use_current_size_for_scrollbar_y = true;
7218
0
            }
7219
77.3k
        window->ResizeBorderHovered = (signed char)border_hovered;
7220
77.3k
        window->ResizeBorderHeld = (signed char)border_held;
7221
7222
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7223
77.3k
        if (window->ViewportOwned)
7224
0
        {
7225
0
            if (!window->Viewport->PlatformRequestMove)
7226
0
                window->Viewport->Pos = window->Pos;
7227
0
            if (!window->Viewport->PlatformRequestResize)
7228
0
                window->Viewport->Size = window->Size;
7229
0
            window->Viewport->UpdateWorkRect();
7230
0
            viewport_rect = window->Viewport->GetMainRect();
7231
0
        }
7232
7233
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7234
77.3k
        window->ViewportPos = window->Viewport->Pos;
7235
7236
        // SCROLLBAR VISIBILITY
7237
7238
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7239
77.3k
        if (!window->Collapsed)
7240
77.3k
        {
7241
            // When reading the current size we need to read it after size constraints have been applied.
7242
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7243
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7244
77.3k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7245
77.3k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7246
77.3k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7247
77.3k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7248
77.3k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7249
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7250
77.3k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7251
77.3k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7252
77.3k
            if (window->ScrollbarX && !window->ScrollbarY)
7253
1.25k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7254
77.3k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7255
7256
            // Amend the partially filled window->DecorationXXX values.
7257
77.3k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7258
77.3k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7259
77.3k
        }
7260
7261
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7262
        // Update various regions. Variables they depend on should be set above in this function.
7263
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7264
7265
        // Outer rectangle
7266
        // Not affected by window border size. Used by:
7267
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7268
        // - Begin() initial clipping rect for drawing window background and borders.
7269
        // - Begin() clipping whole child
7270
77.3k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7271
77.3k
        const ImRect outer_rect = window->Rect();
7272
77.3k
        const ImRect title_bar_rect = window->TitleBarRect();
7273
77.3k
        window->OuterRectClipped = outer_rect;
7274
77.3k
        if (window->DockIsActive)
7275
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7276
77.3k
        window->OuterRectClipped.ClipWith(host_rect);
7277
7278
        // Inner rectangle
7279
        // Not affected by window border size. Used by:
7280
        // - InnerClipRect
7281
        // - ScrollToRectEx()
7282
        // - NavUpdatePageUpPageDown()
7283
        // - Scrollbar()
7284
77.3k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7285
77.3k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7286
77.3k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7287
77.3k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7288
7289
        // Inner clipping rectangle.
7290
        // Will extend a little bit outside the normal work region.
7291
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7292
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7293
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7294
        // Affected by window/frame border size. Used by:
7295
        // - Begin() initial clip rect
7296
77.3k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7297
77.3k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7298
77.3k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7299
77.3k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImTrunc(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7300
77.3k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7301
77.3k
        window->InnerClipRect.ClipWithFull(host_rect);
7302
7303
        // Default item width. Make it proportional to window size if window manually resizes
7304
77.3k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7305
77.3k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7306
0
        else
7307
0
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7308
7309
        // SCROLLING
7310
7311
        // Lock down maximum scrolling
7312
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7313
        // for right/bottom aligned items without creating a scrollbar.
7314
77.3k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7315
77.3k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7316
7317
        // Apply scrolling
7318
77.3k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7319
77.3k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7320
77.3k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7321
7322
        // DRAWING
7323
7324
        // Setup draw list and outer clipping rectangle
7325
77.3k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7326
77.3k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7327
77.3k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7328
7329
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7330
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7331
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7332
77.3k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7333
77.3k
        if (is_undocked_or_docked_visible)
7334
77.3k
        {
7335
77.3k
            bool render_decorations_in_parent = false;
7336
77.3k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7337
25.7k
            {
7338
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7339
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7340
25.7k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7341
25.7k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7342
25.7k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7343
25.7k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7344
25.7k
                    render_decorations_in_parent = true;
7345
25.7k
            }
7346
77.3k
            if (render_decorations_in_parent)
7347
25.7k
                window->DrawList = parent_window->DrawList;
7348
7349
            // Handle title bar, scrollbar, resize grips and resize borders
7350
77.3k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7351
77.3k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7352
77.3k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7353
7354
77.3k
            if (render_decorations_in_parent)
7355
25.7k
                window->DrawList = &window->DrawListInst;
7356
77.3k
        }
7357
7358
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7359
7360
        // Work rectangle.
7361
        // Affected by window padding and border size. Used by:
7362
        // - Columns() for right-most edge
7363
        // - TreeNode(), CollapsingHeader() for right-most edge
7364
        // - BeginTabBar() for right-most edge
7365
77.3k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7366
77.3k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7367
77.3k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7368
77.3k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7369
77.3k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7370
77.3k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7371
77.3k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7372
77.3k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7373
77.3k
        window->ParentWorkRect = window->WorkRect;
7374
7375
        // [LEGACY] Content Region
7376
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7377
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7378
        // Used by:
7379
        // - Mouse wheel scrolling + many other things
7380
77.3k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7381
77.3k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7382
77.3k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7383
77.3k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7384
7385
        // Setup drawing context
7386
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7387
77.3k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7388
77.3k
        window->DC.GroupOffset.x = 0.0f;
7389
77.3k
        window->DC.ColumnsOffset.x = 0.0f;
7390
7391
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7392
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7393
77.3k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7394
77.3k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7395
77.3k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7396
77.3k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7397
77.3k
        window->DC.CursorPos = window->DC.CursorStartPos;
7398
77.3k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7399
77.3k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7400
77.3k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7401
77.3k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7402
77.3k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7403
77.3k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7404
7405
77.3k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7406
77.3k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7407
77.3k
        window->DC.NavLayersActiveMaskNext = 0x00;
7408
77.3k
        window->DC.NavIsScrollPushableX = true;
7409
77.3k
        window->DC.NavHideHighlightOneFrame = false;
7410
77.3k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7411
7412
77.3k
        window->DC.MenuBarAppending = false;
7413
77.3k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7414
77.3k
        window->DC.TreeDepth = 0;
7415
77.3k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7416
77.3k
        window->DC.ChildWindows.resize(0);
7417
77.3k
        window->DC.StateStorage = &window->StateStorage;
7418
77.3k
        window->DC.CurrentColumns = NULL;
7419
77.3k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7420
77.3k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7421
7422
77.3k
        window->DC.ItemWidth = window->ItemWidthDefault;
7423
77.3k
        window->DC.TextWrapPos = -1.0f; // disabled
7424
77.3k
        window->DC.ItemWidthStack.resize(0);
7425
77.3k
        window->DC.TextWrapPosStack.resize(0);
7426
7427
77.3k
        if (window->AutoFitFramesX > 0)
7428
2
            window->AutoFitFramesX--;
7429
77.3k
        if (window->AutoFitFramesY > 0)
7430
2
            window->AutoFitFramesY--;
7431
7432
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7433
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7434
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7435
        // - Position window behind the modal that is not a begin-parent of this window.
7436
77.3k
        if (want_focus)
7437
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7438
77.3k
        if (want_focus && window == g.NavWindow)
7439
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7440
7441
        // Close requested by platform window (apply to all windows in this viewport)
7442
77.3k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7443
0
        {
7444
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7445
0
            *p_open = false;
7446
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7447
0
        }
7448
7449
        // Title bar
7450
77.3k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7451
51.5k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7452
7453
        // Clear hit test shape every frame
7454
77.3k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7455
7456
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7457
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7458
        // Maybe we can support CTRL+C on every element?
7459
        /*
7460
        //if (g.NavWindow == window && g.ActiveId == 0)
7461
        if (g.ActiveId == window->MoveId)
7462
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7463
                LogToClipboard();
7464
        */
7465
7466
77.3k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7467
77.3k
        {
7468
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7469
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7470
77.3k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7471
0
                BeginDockableDragDropSource(window);
7472
7473
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7474
77.3k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7475
0
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7476
0
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7477
0
                        BeginDockableDragDropTarget(window);
7478
77.3k
        }
7479
7480
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7481
        // This is useful to allow creating context menus on title bar only, etc.
7482
77.3k
        if (window->DockIsActive)
7483
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7484
77.3k
        else
7485
77.3k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7486
7487
        // [DEBUG]
7488
77.3k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7489
77.3k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7490
0
            DebugLocateItemResolveWithLastItem();
7491
77.3k
#endif
7492
7493
        // [Test Engine] Register title bar / tab with MoveId.
7494
#ifdef IMGUI_ENABLE_TEST_ENGINE
7495
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7496
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7497
#endif
7498
77.3k
    }
7499
0
    else
7500
0
    {
7501
        // Append
7502
0
        SetCurrentViewport(window, window->Viewport);
7503
0
        SetCurrentWindow(window);
7504
0
    }
7505
7506
77.3k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7507
77.3k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7508
7509
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7510
77.3k
    window->WriteAccessed = false;
7511
77.3k
    window->BeginCount++;
7512
77.3k
    g.NextWindowData.ClearFlags();
7513
7514
    // Update visibility
7515
77.3k
    if (first_begin_of_the_frame)
7516
77.3k
    {
7517
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7518
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7519
        // This is analogous to regular windows being hidden from one frame.
7520
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7521
77.3k
        if (window->DockIsActive && !window->DockTabIsVisible)
7522
0
        {
7523
0
            if (window->LastFrameJustFocused == g.FrameCount)
7524
0
                window->HiddenFramesCannotSkipItems = 1;
7525
0
            else
7526
0
                window->HiddenFramesCanSkipItems = 1;
7527
0
        }
7528
7529
77.3k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7530
25.7k
        {
7531
            // Child window can be out of sight and have "negative" clip windows.
7532
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7533
25.7k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7534
25.7k
            const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7535
25.7k
            if (!g.LogEnabled && !nav_request)
7536
25.7k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7537
0
                {
7538
0
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7539
0
                        window->HiddenFramesCannotSkipItems = 1;
7540
0
                    else
7541
0
                        window->HiddenFramesCanSkipItems = 1;
7542
0
                }
7543
7544
            // Hide along with parent or if parent is collapsed
7545
25.7k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7546
0
                window->HiddenFramesCanSkipItems = 1;
7547
25.7k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7548
1
                window->HiddenFramesCannotSkipItems = 1;
7549
25.7k
        }
7550
7551
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7552
77.3k
        if (style.Alpha <= 0.0f)
7553
0
            window->HiddenFramesCanSkipItems = 1;
7554
7555
        // Update the Hidden flag
7556
77.3k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7557
77.3k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7558
7559
        // Disable inputs for requested number of frames
7560
77.3k
        if (window->DisableInputsFrames > 0)
7561
0
        {
7562
0
            window->DisableInputsFrames--;
7563
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7564
0
        }
7565
7566
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7567
77.3k
        bool skip_items = false;
7568
77.3k
        if (window->Collapsed || !window->Active || hidden_regular)
7569
2
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7570
0
                skip_items = true;
7571
77.3k
        window->SkipItems = skip_items;
7572
7573
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7574
77.3k
        if (window->SkipItems)
7575
0
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7576
7577
        // Sanity check: there are two spots which can set Appearing = true
7578
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7579
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7580
77.3k
        if (window->SkipItems && !window->Appearing)
7581
77.3k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7582
77.3k
    }
7583
7584
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7585
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7586
77.3k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7587
0
    {
7588
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7589
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7590
0
        return false;
7591
0
    }
7592
7593
77.3k
    return !window->SkipItems;
7594
77.3k
}
7595
7596
void ImGui::End()
7597
77.3k
{
7598
77.3k
    ImGuiContext& g = *GImGui;
7599
77.3k
    ImGuiWindow* window = g.CurrentWindow;
7600
7601
    // Error checking: verify that user hasn't called End() too many times!
7602
77.3k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7603
0
    {
7604
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7605
0
        return;
7606
0
    }
7607
77.3k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7608
7609
    // Error checking: verify that user doesn't directly call End() on a child window.
7610
77.3k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7611
77.3k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7612
7613
    // Close anything that is open
7614
77.3k
    if (window->DC.CurrentColumns)
7615
0
        EndColumns();
7616
77.3k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7617
77.3k
        PopClipRect();
7618
77.3k
    PopFocusScope();
7619
7620
    // Stop logging
7621
77.3k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7622
51.5k
        LogFinish();
7623
7624
77.3k
    if (window->DC.IsSetPos)
7625
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7626
7627
    // Docking: report contents sizes to parent to allow for auto-resize
7628
77.3k
    if (window->DockNode && window->DockTabIsVisible)
7629
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7630
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7631
7632
    // Pop from window stack
7633
77.3k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7634
77.3k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7635
0
        g.BeginMenuCount--;
7636
77.3k
    if (window->Flags & ImGuiWindowFlags_Popup)
7637
0
        g.BeginPopupStack.pop_back();
7638
77.3k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7639
77.3k
    g.CurrentWindowStack.pop_back();
7640
77.3k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7641
77.3k
    if (g.CurrentWindow)
7642
51.5k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7643
77.3k
}
7644
7645
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7646
9.00k
{
7647
9.00k
    ImGuiContext& g = *GImGui;
7648
9.00k
    IM_ASSERT(window == window->RootWindow);
7649
7650
9.00k
    const int cur_order = window->FocusOrder;
7651
9.00k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7652
9.00k
    if (g.WindowsFocusOrder.back() == window)
7653
9.00k
        return;
7654
7655
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7656
0
    for (int n = cur_order; n < new_order; n++)
7657
0
    {
7658
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7659
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7660
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7661
0
    }
7662
0
    g.WindowsFocusOrder[new_order] = window;
7663
0
    window->FocusOrder = (short)new_order;
7664
0
}
7665
7666
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7667
9.00k
{
7668
9.00k
    ImGuiContext& g = *GImGui;
7669
9.00k
    ImGuiWindow* current_front_window = g.Windows.back();
7670
9.00k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7671
9.00k
        return;
7672
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7673
0
        if (g.Windows[i] == window)
7674
0
        {
7675
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7676
0
            g.Windows[g.Windows.Size - 1] = window;
7677
0
            break;
7678
0
        }
7679
0
}
7680
7681
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7682
0
{
7683
0
    ImGuiContext& g = *GImGui;
7684
0
    if (g.Windows[0] == window)
7685
0
        return;
7686
0
    for (int i = 0; i < g.Windows.Size; i++)
7687
0
        if (g.Windows[i] == window)
7688
0
        {
7689
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7690
0
            g.Windows[0] = window;
7691
0
            break;
7692
0
        }
7693
0
}
7694
7695
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7696
0
{
7697
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7698
0
    ImGuiContext& g = *GImGui;
7699
0
    window = window->RootWindow;
7700
0
    behind_window = behind_window->RootWindow;
7701
0
    int pos_wnd = FindWindowDisplayIndex(window);
7702
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7703
0
    if (pos_wnd < pos_beh)
7704
0
    {
7705
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7706
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7707
0
        g.Windows[pos_beh - 1] = window;
7708
0
    }
7709
0
    else
7710
0
    {
7711
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7712
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7713
0
        g.Windows[pos_beh] = window;
7714
0
    }
7715
0
}
7716
7717
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7718
0
{
7719
0
    ImGuiContext& g = *GImGui;
7720
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7721
0
}
7722
7723
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7724
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7725
10.4k
{
7726
10.4k
    ImGuiContext& g = *GImGui;
7727
7728
    // Modal check?
7729
10.4k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7730
601
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7731
0
        {
7732
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7733
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7734
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7735
0
            return;
7736
0
        }
7737
7738
    // Find last focused child (if any) and focus it instead.
7739
10.4k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7740
0
        window = NavRestoreLastChildNavWindow(window);
7741
7742
    // Apply focus
7743
10.4k
    if (g.NavWindow != window)
7744
2.67k
    {
7745
2.67k
        SetNavWindow(window);
7746
2.67k
        if (window && g.NavDisableMouseHover)
7747
168
            g.NavMousePosDirty = true;
7748
2.67k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7749
2.67k
        g.NavLayer = ImGuiNavLayer_Main;
7750
2.67k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7751
2.67k
        g.NavIdIsAlive = false;
7752
2.67k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
7753
7754
        // Close popups if any
7755
2.67k
        ClosePopupsOverWindow(window, false);
7756
2.67k
    }
7757
7758
    // Move the root window to the top of the pile
7759
10.4k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7760
10.4k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7761
10.4k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7762
10.4k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7763
10.4k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7764
7765
    // Steal active widgets. Some of the cases it triggers includes:
7766
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7767
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7768
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7769
10.4k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7770
12
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7771
12
            ClearActiveID();
7772
7773
    // Passing NULL allow to disable keyboard focus
7774
10.4k
    if (!window)
7775
1.43k
        return;
7776
9.00k
    window->LastFrameJustFocused = g.FrameCount;
7777
7778
    // Select in dock node
7779
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
7780
    //if (dock_node && dock_node->TabBar)
7781
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7782
7783
    // Bring to front
7784
9.00k
    BringWindowToFocusFront(focus_front_window);
7785
9.00k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7786
9.00k
        BringWindowToDisplayFront(display_front_window);
7787
9.00k
}
7788
7789
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7790
0
{
7791
0
    ImGuiContext& g = *GImGui;
7792
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7793
0
    if (under_this_window != NULL)
7794
0
    {
7795
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7796
0
        int offset = -1;
7797
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7798
0
        {
7799
0
            under_this_window = under_this_window->ParentWindow;
7800
0
            offset = 0;
7801
0
        }
7802
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7803
0
    }
7804
0
    for (int i = start_idx; i >= 0; i--)
7805
0
    {
7806
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7807
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7808
0
        if (window == ignore_window || !window->WasActive)
7809
0
            continue;
7810
0
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7811
0
            continue;
7812
0
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7813
0
        {
7814
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7815
            // This is failing (lagging by one frame) for docked windows.
7816
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7817
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7818
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7819
0
            FocusWindow(window, flags);
7820
0
            return;
7821
0
        }
7822
0
    }
7823
0
    FocusWindow(NULL, flags);
7824
0
}
7825
7826
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7827
void ImGui::SetCurrentFont(ImFont* font)
7828
25.7k
{
7829
25.7k
    ImGuiContext& g = *GImGui;
7830
25.7k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7831
25.7k
    IM_ASSERT(font->Scale > 0.0f);
7832
25.7k
    g.Font = font;
7833
25.7k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7834
25.7k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7835
7836
25.7k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7837
25.7k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7838
25.7k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7839
25.7k
    g.DrawListSharedData.Font = g.Font;
7840
25.7k
    g.DrawListSharedData.FontSize = g.FontSize;
7841
25.7k
}
7842
7843
void ImGui::PushFont(ImFont* font)
7844
0
{
7845
0
    ImGuiContext& g = *GImGui;
7846
0
    if (!font)
7847
0
        font = GetDefaultFont();
7848
0
    SetCurrentFont(font);
7849
0
    g.FontStack.push_back(font);
7850
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7851
0
}
7852
7853
void  ImGui::PopFont()
7854
0
{
7855
0
    ImGuiContext& g = *GImGui;
7856
0
    g.CurrentWindow->DrawList->PopTextureID();
7857
0
    g.FontStack.pop_back();
7858
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7859
0
}
7860
7861
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7862
25.7k
{
7863
25.7k
    ImGuiContext& g = *GImGui;
7864
25.7k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7865
25.7k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7866
25.7k
    if (enabled)
7867
0
        item_flags |= option;
7868
25.7k
    else
7869
25.7k
        item_flags &= ~option;
7870
25.7k
    g.CurrentItemFlags = item_flags;
7871
25.7k
    g.ItemFlagsStack.push_back(item_flags);
7872
25.7k
}
7873
7874
void ImGui::PopItemFlag()
7875
25.7k
{
7876
25.7k
    ImGuiContext& g = *GImGui;
7877
25.7k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7878
25.7k
    g.ItemFlagsStack.pop_back();
7879
25.7k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7880
25.7k
}
7881
7882
// BeginDisabled()/EndDisabled()
7883
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7884
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7885
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7886
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7887
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7888
void ImGui::BeginDisabled(bool disabled)
7889
0
{
7890
0
    ImGuiContext& g = *GImGui;
7891
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7892
0
    if (!was_disabled && disabled)
7893
0
    {
7894
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7895
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7896
0
    }
7897
0
    if (was_disabled || disabled)
7898
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7899
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7900
0
    g.DisabledStackSize++;
7901
0
}
7902
7903
void ImGui::EndDisabled()
7904
0
{
7905
0
    ImGuiContext& g = *GImGui;
7906
0
    IM_ASSERT(g.DisabledStackSize > 0);
7907
0
    g.DisabledStackSize--;
7908
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7909
    //PopItemFlag();
7910
0
    g.ItemFlagsStack.pop_back();
7911
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7912
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7913
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7914
0
}
7915
7916
void ImGui::PushTabStop(bool tab_stop)
7917
25.7k
{
7918
25.7k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7919
25.7k
}
7920
7921
void ImGui::PopTabStop()
7922
25.7k
{
7923
25.7k
    PopItemFlag();
7924
25.7k
}
7925
7926
void ImGui::PushButtonRepeat(bool repeat)
7927
0
{
7928
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7929
0
}
7930
7931
void ImGui::PopButtonRepeat()
7932
0
{
7933
0
    PopItemFlag();
7934
0
}
7935
7936
void ImGui::PushTextWrapPos(float wrap_pos_x)
7937
0
{
7938
0
    ImGuiWindow* window = GetCurrentWindow();
7939
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7940
0
    window->DC.TextWrapPos = wrap_pos_x;
7941
0
}
7942
7943
void ImGui::PopTextWrapPos()
7944
0
{
7945
0
    ImGuiWindow* window = GetCurrentWindow();
7946
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7947
0
    window->DC.TextWrapPosStack.pop_back();
7948
0
}
7949
7950
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7951
0
{
7952
0
    ImGuiWindow* last_window = NULL;
7953
0
    while (last_window != window)
7954
0
    {
7955
0
        last_window = window;
7956
0
        window = window->RootWindow;
7957
0
        if (popup_hierarchy)
7958
0
            window = window->RootWindowPopupTree;
7959
0
    if (dock_hierarchy)
7960
0
      window = window->RootWindowDockTree;
7961
0
  }
7962
0
    return window;
7963
0
}
7964
7965
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7966
0
{
7967
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7968
0
    if (window_root == potential_parent)
7969
0
        return true;
7970
0
    while (window != NULL)
7971
0
    {
7972
0
        if (window == potential_parent)
7973
0
            return true;
7974
0
        if (window == window_root) // end of chain
7975
0
            return false;
7976
0
        window = window->ParentWindow;
7977
0
    }
7978
0
    return false;
7979
0
}
7980
7981
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7982
0
{
7983
0
    if (window->RootWindow == potential_parent)
7984
0
        return true;
7985
0
    while (window != NULL)
7986
0
    {
7987
0
        if (window == potential_parent)
7988
0
            return true;
7989
0
        window = window->ParentWindowInBeginStack;
7990
0
    }
7991
0
    return false;
7992
0
}
7993
7994
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7995
0
{
7996
0
    ImGuiContext& g = *GImGui;
7997
7998
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7999
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8000
0
    if (display_layer_delta != 0)
8001
0
        return display_layer_delta > 0;
8002
8003
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8004
0
    {
8005
0
        ImGuiWindow* candidate_window = g.Windows[i];
8006
0
        if (candidate_window == potential_above)
8007
0
            return true;
8008
0
        if (candidate_window == potential_below)
8009
0
            return false;
8010
0
    }
8011
0
    return false;
8012
0
}
8013
8014
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8015
47.9k
{
8016
47.9k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8017
8018
47.9k
    ImGuiContext& g = *GImGui;
8019
47.9k
    ImGuiWindow* ref_window = g.HoveredWindow;
8020
47.9k
    ImGuiWindow* cur_window = g.CurrentWindow;
8021
47.9k
    if (ref_window == NULL)
8022
43.3k
        return false;
8023
8024
4.57k
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8025
4.57k
    {
8026
4.57k
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8027
4.57k
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8028
4.57k
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8029
4.57k
        if (flags & ImGuiHoveredFlags_RootWindow)
8030
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8031
8032
4.57k
        bool result;
8033
4.57k
        if (flags & ImGuiHoveredFlags_ChildWindows)
8034
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8035
4.57k
        else
8036
4.57k
            result = (ref_window == cur_window);
8037
4.57k
        if (!result)
8038
4.57k
            return false;
8039
4.57k
    }
8040
8041
0
    if (!IsWindowContentHoverable(ref_window, flags))
8042
0
        return false;
8043
0
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8044
0
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8045
0
            return false;
8046
8047
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8048
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8049
    // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
8050
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8051
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8052
0
    if (flags & ImGuiHoveredFlags_ForTooltip)
8053
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8054
0
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8055
0
        return false;
8056
8057
0
    return true;
8058
0
}
8059
8060
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8061
50.4k
{
8062
50.4k
    ImGuiContext& g = *GImGui;
8063
50.4k
    ImGuiWindow* ref_window = g.NavWindow;
8064
50.4k
    ImGuiWindow* cur_window = g.CurrentWindow;
8065
8066
50.4k
    if (ref_window == NULL)
8067
4.63k
        return false;
8068
45.7k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8069
0
        return true;
8070
8071
45.7k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8072
45.7k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8073
45.7k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8074
45.7k
    if (flags & ImGuiHoveredFlags_RootWindow)
8075
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8076
8077
45.7k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8078
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8079
45.7k
    else
8080
45.7k
        return (ref_window == cur_window);
8081
45.7k
}
8082
8083
ImGuiID ImGui::GetWindowDockID()
8084
0
{
8085
0
    ImGuiContext& g = *GImGui;
8086
0
    return g.CurrentWindow->DockId;
8087
0
}
8088
8089
bool ImGui::IsWindowDocked()
8090
0
{
8091
0
    ImGuiContext& g = *GImGui;
8092
0
    return g.CurrentWindow->DockIsActive;
8093
0
}
8094
8095
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8096
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8097
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8098
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8099
0
{
8100
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8101
0
}
8102
8103
float ImGui::GetWindowWidth()
8104
8.92k
{
8105
8.92k
    ImGuiWindow* window = GImGui->CurrentWindow;
8106
8.92k
    return window->Size.x;
8107
8.92k
}
8108
8109
float ImGui::GetWindowHeight()
8110
11.2k
{
8111
11.2k
    ImGuiWindow* window = GImGui->CurrentWindow;
8112
11.2k
    return window->Size.y;
8113
11.2k
}
8114
8115
ImVec2 ImGui::GetWindowPos()
8116
0
{
8117
0
    ImGuiContext& g = *GImGui;
8118
0
    ImGuiWindow* window = g.CurrentWindow;
8119
0
    return window->Pos;
8120
0
}
8121
8122
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8123
0
{
8124
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8125
0
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8126
0
        return;
8127
8128
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8129
0
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8130
0
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8131
8132
    // Set
8133
0
    const ImVec2 old_pos = window->Pos;
8134
0
    window->Pos = ImTrunc(pos);
8135
0
    ImVec2 offset = window->Pos - old_pos;
8136
0
    if (offset.x == 0.0f && offset.y == 0.0f)
8137
0
        return;
8138
0
    MarkIniSettingsDirty(window);
8139
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8140
0
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8141
0
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8142
0
    window->DC.IdealMaxPos += offset;
8143
0
    window->DC.CursorStartPos += offset;
8144
0
}
8145
8146
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8147
0
{
8148
0
    ImGuiWindow* window = GetCurrentWindowRead();
8149
0
    SetWindowPos(window, pos, cond);
8150
0
}
8151
8152
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8153
0
{
8154
0
    if (ImGuiWindow* window = FindWindowByName(name))
8155
0
        SetWindowPos(window, pos, cond);
8156
0
}
8157
8158
ImVec2 ImGui::GetWindowSize()
8159
0
{
8160
0
    ImGuiWindow* window = GetCurrentWindowRead();
8161
0
    return window->Size;
8162
0
}
8163
8164
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8165
51.5k
{
8166
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8167
51.5k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8168
25.7k
        return;
8169
8170
25.7k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8171
25.7k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8172
8173
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8174
25.7k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8175
2
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8176
25.7k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8177
2
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8178
8179
    // Set
8180
25.7k
    ImVec2 old_size = window->SizeFull;
8181
25.7k
    if (size.x <= 0.0f)
8182
0
        window->AutoFitOnlyGrows = false;
8183
25.7k
    else
8184
25.7k
        window->SizeFull.x = IM_TRUNC(size.x);
8185
25.7k
    if (size.y <= 0.0f)
8186
0
        window->AutoFitOnlyGrows = false;
8187
25.7k
    else
8188
25.7k
        window->SizeFull.y = IM_TRUNC(size.y);
8189
25.7k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8190
25.3k
        MarkIniSettingsDirty(window);
8191
25.7k
}
8192
8193
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8194
0
{
8195
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8196
0
}
8197
8198
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8199
0
{
8200
0
    if (ImGuiWindow* window = FindWindowByName(name))
8201
0
        SetWindowSize(window, size, cond);
8202
0
}
8203
8204
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8205
0
{
8206
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8207
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8208
0
        return;
8209
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8210
8211
    // Set
8212
0
    window->Collapsed = collapsed;
8213
0
}
8214
8215
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8216
0
{
8217
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8218
0
    window->HitTestHoleSize = ImVec2ih(size);
8219
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8220
0
}
8221
8222
void ImGui::SetWindowHiddendAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8223
0
{
8224
0
    window->Hidden = window->SkipItems = true;
8225
0
    window->HiddenFramesCanSkipItems = 1;
8226
0
}
8227
8228
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8229
0
{
8230
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8231
0
}
8232
8233
bool ImGui::IsWindowCollapsed()
8234
0
{
8235
0
    ImGuiWindow* window = GetCurrentWindowRead();
8236
0
    return window->Collapsed;
8237
0
}
8238
8239
bool ImGui::IsWindowAppearing()
8240
0
{
8241
0
    ImGuiWindow* window = GetCurrentWindowRead();
8242
0
    return window->Appearing;
8243
0
}
8244
8245
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8246
0
{
8247
0
    if (ImGuiWindow* window = FindWindowByName(name))
8248
0
        SetWindowCollapsed(window, collapsed, cond);
8249
0
}
8250
8251
void ImGui::SetWindowFocus()
8252
8.92k
{
8253
8.92k
    FocusWindow(GImGui->CurrentWindow);
8254
8.92k
}
8255
8256
void ImGui::SetWindowFocus(const char* name)
8257
0
{
8258
0
    if (name)
8259
0
    {
8260
0
        if (ImGuiWindow* window = FindWindowByName(name))
8261
0
            FocusWindow(window);
8262
0
    }
8263
0
    else
8264
0
    {
8265
0
        FocusWindow(NULL);
8266
0
    }
8267
0
}
8268
8269
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8270
0
{
8271
0
    ImGuiContext& g = *GImGui;
8272
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8273
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8274
0
    g.NextWindowData.PosVal = pos;
8275
0
    g.NextWindowData.PosPivotVal = pivot;
8276
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8277
0
    g.NextWindowData.PosUndock = true;
8278
0
}
8279
8280
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8281
51.5k
{
8282
51.5k
    ImGuiContext& g = *GImGui;
8283
51.5k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8284
51.5k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8285
51.5k
    g.NextWindowData.SizeVal = size;
8286
51.5k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8287
51.5k
}
8288
8289
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8290
0
{
8291
0
    ImGuiContext& g = *GImGui;
8292
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8293
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8294
0
    g.NextWindowData.SizeCallback = custom_callback;
8295
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8296
0
}
8297
8298
// Content size = inner scrollable rectangle, padded with WindowPadding.
8299
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8300
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8301
0
{
8302
0
    ImGuiContext& g = *GImGui;
8303
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8304
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8305
0
}
8306
8307
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8308
0
{
8309
0
    ImGuiContext& g = *GImGui;
8310
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8311
0
    g.NextWindowData.ScrollVal = scroll;
8312
0
}
8313
8314
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8315
0
{
8316
0
    ImGuiContext& g = *GImGui;
8317
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8318
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8319
0
    g.NextWindowData.CollapsedVal = collapsed;
8320
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8321
0
}
8322
8323
void ImGui::SetNextWindowFocus()
8324
0
{
8325
0
    ImGuiContext& g = *GImGui;
8326
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8327
0
}
8328
8329
void ImGui::SetNextWindowBgAlpha(float alpha)
8330
0
{
8331
0
    ImGuiContext& g = *GImGui;
8332
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8333
0
    g.NextWindowData.BgAlphaVal = alpha;
8334
0
}
8335
8336
void ImGui::SetNextWindowViewport(ImGuiID id)
8337
0
{
8338
0
    ImGuiContext& g = *GImGui;
8339
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8340
0
    g.NextWindowData.ViewportId = id;
8341
0
}
8342
8343
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8344
0
{
8345
0
    ImGuiContext& g = *GImGui;
8346
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8347
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8348
0
    g.NextWindowData.DockId = id;
8349
0
}
8350
8351
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8352
0
{
8353
0
    ImGuiContext& g = *GImGui;
8354
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8355
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8356
0
    g.NextWindowData.WindowClass = *window_class;
8357
0
}
8358
8359
ImDrawList* ImGui::GetWindowDrawList()
8360
25.7k
{
8361
25.7k
    ImGuiWindow* window = GetCurrentWindow();
8362
25.7k
    return window->DrawList;
8363
25.7k
}
8364
8365
float ImGui::GetWindowDpiScale()
8366
0
{
8367
0
    ImGuiContext& g = *GImGui;
8368
0
    return g.CurrentDpiScale;
8369
0
}
8370
8371
ImGuiViewport* ImGui::GetWindowViewport()
8372
0
{
8373
0
    ImGuiContext& g = *GImGui;
8374
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8375
0
    return g.CurrentViewport;
8376
0
}
8377
8378
ImFont* ImGui::GetFont()
8379
18.8M
{
8380
18.8M
    return GImGui->Font;
8381
18.8M
}
8382
8383
float ImGui::GetFontSize()
8384
18.8M
{
8385
18.8M
    return GImGui->FontSize;
8386
18.8M
}
8387
8388
ImVec2 ImGui::GetFontTexUvWhitePixel()
8389
0
{
8390
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8391
0
}
8392
8393
void ImGui::SetWindowFontScale(float scale)
8394
0
{
8395
0
    IM_ASSERT(scale > 0.0f);
8396
0
    ImGuiContext& g = *GImGui;
8397
0
    ImGuiWindow* window = GetCurrentWindow();
8398
0
    window->FontWindowScale = scale;
8399
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8400
0
}
8401
8402
void ImGui::PushFocusScope(ImGuiID id)
8403
77.3k
{
8404
77.3k
    ImGuiContext& g = *GImGui;
8405
77.3k
    g.FocusScopeStack.push_back(id);
8406
77.3k
    g.CurrentFocusScopeId = id;
8407
77.3k
}
8408
8409
void ImGui::PopFocusScope()
8410
77.3k
{
8411
77.3k
    ImGuiContext& g = *GImGui;
8412
77.3k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8413
77.3k
    g.FocusScopeStack.pop_back();
8414
77.3k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8415
77.3k
}
8416
8417
// Focus = move navigation cursor, set scrolling, set focus window.
8418
void ImGui::FocusItem()
8419
0
{
8420
0
    ImGuiContext& g = *GImGui;
8421
0
    ImGuiWindow* window = g.CurrentWindow;
8422
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8423
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8424
0
    {
8425
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8426
0
        return;
8427
0
    }
8428
8429
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8430
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8431
0
    SetNavWindow(window);
8432
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8433
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8434
0
}
8435
8436
void ImGui::ActivateItemByID(ImGuiID id)
8437
0
{
8438
0
    ImGuiContext& g = *GImGui;
8439
0
    g.NavNextActivateId = id;
8440
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8441
0
}
8442
8443
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8444
// But ActivateItem() should function without altering scroll/focus?
8445
void ImGui::SetKeyboardFocusHere(int offset)
8446
0
{
8447
0
    ImGuiContext& g = *GImGui;
8448
0
    ImGuiWindow* window = g.CurrentWindow;
8449
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8450
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8451
8452
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8453
    // When we refactor this function into ActivateItem() we may want to make this an option.
8454
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8455
    // is also automatically dropped in the event g.ActiveId is stolen.
8456
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8457
0
    {
8458
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8459
0
        return;
8460
0
    }
8461
8462
0
    SetNavWindow(window);
8463
8464
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8465
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8466
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8467
0
    if (offset == -1)
8468
0
    {
8469
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8470
0
    }
8471
0
    else
8472
0
    {
8473
0
        g.NavTabbingDir = 1;
8474
0
        g.NavTabbingCounter = offset + 1;
8475
0
    }
8476
0
}
8477
8478
void ImGui::SetItemDefaultFocus()
8479
0
{
8480
0
    ImGuiContext& g = *GImGui;
8481
0
    ImGuiWindow* window = g.CurrentWindow;
8482
0
    if (!window->Appearing)
8483
0
        return;
8484
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8485
0
        return;
8486
8487
0
    g.NavInitRequest = false;
8488
0
    NavApplyItemToResult(&g.NavInitResult);
8489
0
    NavUpdateAnyRequestFlag();
8490
8491
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8492
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8493
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8494
0
}
8495
8496
void ImGui::SetStateStorage(ImGuiStorage* tree)
8497
0
{
8498
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8499
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8500
0
}
8501
8502
ImGuiStorage* ImGui::GetStateStorage()
8503
0
{
8504
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8505
0
    return window->DC.StateStorage;
8506
0
}
8507
8508
void ImGui::PushID(const char* str_id)
8509
25.7k
{
8510
25.7k
    ImGuiContext& g = *GImGui;
8511
25.7k
    ImGuiWindow* window = g.CurrentWindow;
8512
25.7k
    ImGuiID id = window->GetID(str_id);
8513
25.7k
    window->IDStack.push_back(id);
8514
25.7k
}
8515
8516
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8517
0
{
8518
0
    ImGuiContext& g = *GImGui;
8519
0
    ImGuiWindow* window = g.CurrentWindow;
8520
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8521
0
    window->IDStack.push_back(id);
8522
0
}
8523
8524
void ImGui::PushID(const void* ptr_id)
8525
0
{
8526
0
    ImGuiContext& g = *GImGui;
8527
0
    ImGuiWindow* window = g.CurrentWindow;
8528
0
    ImGuiID id = window->GetID(ptr_id);
8529
0
    window->IDStack.push_back(id);
8530
0
}
8531
8532
void ImGui::PushID(int int_id)
8533
0
{
8534
0
    ImGuiContext& g = *GImGui;
8535
0
    ImGuiWindow* window = g.CurrentWindow;
8536
0
    ImGuiID id = window->GetID(int_id);
8537
0
    window->IDStack.push_back(id);
8538
0
}
8539
8540
// Push a given id value ignoring the ID stack as a seed.
8541
void ImGui::PushOverrideID(ImGuiID id)
8542
0
{
8543
0
    ImGuiContext& g = *GImGui;
8544
0
    ImGuiWindow* window = g.CurrentWindow;
8545
0
    if (g.DebugHookIdInfo == id)
8546
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8547
0
    window->IDStack.push_back(id);
8548
0
}
8549
8550
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8551
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8552
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8553
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8554
0
{
8555
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8556
0
    ImGuiContext& g = *GImGui;
8557
0
    if (g.DebugHookIdInfo == id)
8558
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8559
0
    return id;
8560
0
}
8561
8562
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8563
0
{
8564
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8565
0
    ImGuiContext& g = *GImGui;
8566
0
    if (g.DebugHookIdInfo == id)
8567
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8568
0
    return id;
8569
0
}
8570
8571
void ImGui::PopID()
8572
25.7k
{
8573
25.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
8574
25.7k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8575
25.7k
    window->IDStack.pop_back();
8576
25.7k
}
8577
8578
ImGuiID ImGui::GetID(const char* str_id)
8579
0
{
8580
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8581
0
    return window->GetID(str_id);
8582
0
}
8583
8584
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8585
0
{
8586
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8587
0
    return window->GetID(str_id_begin, str_id_end);
8588
0
}
8589
8590
ImGuiID ImGui::GetID(const void* ptr_id)
8591
0
{
8592
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8593
0
    return window->GetID(ptr_id);
8594
0
}
8595
8596
bool ImGui::IsRectVisible(const ImVec2& size)
8597
0
{
8598
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8599
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8600
0
}
8601
8602
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8603
0
{
8604
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8605
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8606
0
}
8607
8608
8609
//-----------------------------------------------------------------------------
8610
// [SECTION] INPUTS
8611
//-----------------------------------------------------------------------------
8612
// - GetKeyData() [Internal]
8613
// - GetKeyIndex() [Internal]
8614
// - GetKeyName()
8615
// - GetKeyChordName() [Internal]
8616
// - CalcTypematicRepeatAmount() [Internal]
8617
// - GetTypematicRepeatRate() [Internal]
8618
// - GetKeyPressedAmount() [Internal]
8619
// - GetKeyMagnitude2d() [Internal]
8620
//-----------------------------------------------------------------------------
8621
// - UpdateKeyRoutingTable() [Internal]
8622
// - GetRoutingIdFromOwnerId() [Internal]
8623
// - GetShortcutRoutingData() [Internal]
8624
// - CalcRoutingScore() [Internal]
8625
// - SetShortcutRouting() [Internal]
8626
// - TestShortcutRouting() [Internal]
8627
//-----------------------------------------------------------------------------
8628
// - IsKeyDown()
8629
// - IsKeyPressed()
8630
// - IsKeyReleased()
8631
//-----------------------------------------------------------------------------
8632
// - IsMouseDown()
8633
// - IsMouseClicked()
8634
// - IsMouseReleased()
8635
// - IsMouseDoubleClicked()
8636
// - GetMouseClickedCount()
8637
// - IsMouseHoveringRect() [Internal]
8638
// - IsMouseDragPastThreshold() [Internal]
8639
// - IsMouseDragging()
8640
// - GetMousePos()
8641
// - SetMousePos() [Internal]
8642
// - GetMousePosOnOpeningCurrentPopup()
8643
// - IsMousePosValid()
8644
// - IsAnyMouseDown()
8645
// - GetMouseDragDelta()
8646
// - ResetMouseDragDelta()
8647
// - GetMouseCursor()
8648
// - SetMouseCursor()
8649
//-----------------------------------------------------------------------------
8650
// - UpdateAliasKey()
8651
// - GetMergedModsFromKeys()
8652
// - UpdateKeyboardInputs()
8653
// - UpdateMouseInputs()
8654
//-----------------------------------------------------------------------------
8655
// - LockWheelingWindow [Internal]
8656
// - FindBestWheelingWindow [Internal]
8657
// - UpdateMouseWheel() [Internal]
8658
//-----------------------------------------------------------------------------
8659
// - SetNextFrameWantCaptureKeyboard()
8660
// - SetNextFrameWantCaptureMouse()
8661
//-----------------------------------------------------------------------------
8662
// - GetInputSourceName() [Internal]
8663
// - DebugPrintInputEvent() [Internal]
8664
// - UpdateInputEvents() [Internal]
8665
//-----------------------------------------------------------------------------
8666
// - GetKeyOwner() [Internal]
8667
// - TestKeyOwner() [Internal]
8668
// - SetKeyOwner() [Internal]
8669
// - SetItemKeyOwner() [Internal]
8670
// - Shortcut() [Internal]
8671
//-----------------------------------------------------------------------------
8672
8673
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8674
1.12M
{
8675
1.12M
    ImGuiContext& g = *ctx;
8676
8677
    // Special storage location for mods
8678
1.12M
    if (key & ImGuiMod_Mask_)
8679
231k
        key = ConvertSingleModFlagToKey(ctx, key);
8680
8681
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8682
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8683
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8684
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8685
#else
8686
1.12M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8687
1.12M
#endif
8688
1.12M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8689
1.12M
}
8690
8691
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8692
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8693
{
8694
    ImGuiContext& g = *GImGui;
8695
    IM_ASSERT(IsNamedKey(key));
8696
    const ImGuiKeyData* key_data = GetKeyData(key);
8697
    return (ImGuiKey)(key_data - g.IO.KeysData);
8698
}
8699
#endif
8700
8701
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8702
static const char* const GKeyNames[] =
8703
{
8704
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8705
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8706
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8707
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8708
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8709
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8710
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
8711
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8712
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8713
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8714
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8715
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8716
    "AppBack", "AppForward",
8717
    "GamepadStart", "GamepadBack",
8718
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8719
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8720
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8721
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8722
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8723
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8724
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8725
};
8726
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8727
8728
const char* ImGui::GetKeyName(ImGuiKey key)
8729
0
{
8730
0
    ImGuiContext& g = *GImGui;
8731
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8732
0
    IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8733
#else
8734
    if (IsLegacyKey(key))
8735
    {
8736
        if (g.IO.KeyMap[key] == -1)
8737
            return "N/A";
8738
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8739
        key = (ImGuiKey)g.IO.KeyMap[key];
8740
    }
8741
#endif
8742
0
    if (key == ImGuiKey_None)
8743
0
        return "None";
8744
0
    if (key & ImGuiMod_Mask_)
8745
0
        key = ConvertSingleModFlagToKey(&g, key);
8746
0
    if (!IsNamedKey(key))
8747
0
        return "Unknown";
8748
8749
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8750
0
}
8751
8752
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8753
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8754
0
{
8755
0
    ImGuiContext& g = *GImGui;
8756
0
    if (key_chord & ImGuiMod_Shortcut)
8757
0
        key_chord = ConvertShortcutMod(key_chord);
8758
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8759
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8760
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8761
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8762
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8763
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8764
0
}
8765
8766
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8767
// t1 = current time (e.g.: g.Time)
8768
// An event is triggered at:
8769
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8770
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8771
23.4k
{
8772
23.4k
    if (t1 == 0.0f)
8773
0
        return 1;
8774
23.4k
    if (t0 >= t1)
8775
0
        return 0;
8776
23.4k
    if (repeat_rate <= 0.0f)
8777
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8778
23.4k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8779
23.4k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8780
23.4k
    const int count = count_t1 - count_t0;
8781
23.4k
    return count;
8782
23.4k
}
8783
8784
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8785
31.3k
{
8786
31.3k
    ImGuiContext& g = *GImGui;
8787
31.3k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8788
31.3k
    {
8789
1.30k
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8790
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8791
30.0k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8792
31.3k
    }
8793
31.3k
}
8794
8795
// Return value representing the number of presses in the last time period, for the given repeat rate
8796
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8797
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8798
23.4k
{
8799
23.4k
    ImGuiContext& g = *GImGui;
8800
23.4k
    const ImGuiKeyData* key_data = GetKeyData(key);
8801
23.4k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8802
0
        return 0;
8803
23.4k
    const float t = key_data->DownDuration;
8804
23.4k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8805
23.4k
}
8806
8807
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8808
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8809
0
{
8810
0
    return ImVec2(
8811
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8812
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8813
0
}
8814
8815
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8816
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8817
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8818
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8819
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8820
25.7k
{
8821
25.7k
    ImGuiContext& g = *GImGui;
8822
25.7k
    rt->EntriesNext.resize(0);
8823
3.99M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8824
3.96M
    {
8825
3.96M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8826
3.96M
        ImGuiKeyRoutingData* routing_entry;
8827
3.96M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8828
0
        {
8829
0
            routing_entry = &rt->Entries[old_routing_idx];
8830
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8831
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8832
0
            routing_entry->RoutingNextScore = 255;
8833
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8834
0
                continue;
8835
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8836
8837
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8838
0
            if (routing_entry->Mods == g.IO.KeyMods)
8839
0
            {
8840
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8841
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8842
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8843
0
            }
8844
0
        }
8845
8846
        // Rewrite linked-list
8847
3.96M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8848
3.96M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8849
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8850
3.96M
    }
8851
25.7k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8852
25.7k
}
8853
8854
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8855
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8856
0
{
8857
0
    ImGuiContext& g = *GImGui;
8858
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8859
0
}
8860
8861
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8862
0
{
8863
    // Majority of shortcuts will be Key + any number of Mods
8864
    // We accept _Single_ mod with ImGuiKey_None.
8865
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8866
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8867
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8868
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8869
0
    ImGuiContext& g = *GImGui;
8870
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8871
0
    ImGuiKeyRoutingData* routing_data;
8872
0
    if (key_chord & ImGuiMod_Shortcut)
8873
0
        key_chord = ConvertShortcutMod(key_chord);
8874
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8875
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8876
0
    if (key == ImGuiKey_None)
8877
0
        key = ConvertSingleModFlagToKey(&g, mods);
8878
0
    IM_ASSERT(IsNamedKey(key));
8879
8880
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8881
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8882
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8883
0
    {
8884
0
        routing_data = &rt->Entries[idx];
8885
0
        if (routing_data->Mods == mods)
8886
0
            return routing_data;
8887
0
    }
8888
8889
    // Add to linked-list
8890
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8891
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8892
0
    routing_data = &rt->Entries[routing_data_idx];
8893
0
    routing_data->Mods = (ImU16)mods;
8894
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8895
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8896
0
    return routing_data;
8897
0
}
8898
8899
// Current score encoding (lower is highest priority):
8900
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8901
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8902
//  -   2: ImGuiInputFlags_RouteGlobal
8903
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8904
//  - 254: ImGuiInputFlags_RouteGlobalLow
8905
//  - 255: never route
8906
// 'flags' should include an explicit routing policy
8907
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8908
0
{
8909
0
    if (flags & ImGuiInputFlags_RouteFocused)
8910
0
    {
8911
0
        ImGuiContext& g = *GImGui;
8912
0
        ImGuiWindow* focused = g.NavWindow;
8913
8914
        // ActiveID gets top priority
8915
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8916
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8917
0
            return 1;
8918
8919
        // Score based on distance to focused window (lower is better)
8920
        // Assuming both windows are submitting a routing request,
8921
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8922
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8923
        // Assuming only WindowA is submitting a routing request,
8924
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8925
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8926
0
            for (int next_score = 3; focused != NULL; next_score++)
8927
0
            {
8928
0
                if (focused == location)
8929
0
                {
8930
0
                    IM_ASSERT(next_score < 255);
8931
0
                    return next_score;
8932
0
                }
8933
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8934
0
            }
8935
0
        return 255;
8936
0
    }
8937
8938
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8939
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8940
0
        return 2;
8941
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8942
0
        return 254;
8943
0
    return 0;
8944
0
}
8945
8946
// Request a desired route for an input chord (key + mods).
8947
// Return true if the route is available this frame.
8948
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8949
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8950
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8951
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8952
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8953
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8954
51.5k
{
8955
51.5k
    ImGuiContext& g = *GImGui;
8956
51.5k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8957
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8958
51.5k
    else
8959
51.5k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8960
8961
51.5k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8962
0
        if (g.NavWindow == NULL)
8963
0
            return false;
8964
51.5k
    if (flags & ImGuiInputFlags_RouteAlways)
8965
51.5k
        return true;
8966
8967
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8968
0
    if (score == 255)
8969
0
        return false;
8970
8971
    // Submit routing for NEXT frame (assuming score is sufficient)
8972
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8973
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8974
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8975
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8976
0
    if (score < routing_data->RoutingNextScore)
8977
0
    {
8978
0
        routing_data->RoutingNext = routing_id;
8979
0
        routing_data->RoutingNextScore = (ImU8)score;
8980
0
    }
8981
8982
    // Return routing state for CURRENT frame
8983
0
    return routing_data->RoutingCurr == routing_id;
8984
0
}
8985
8986
// Currently unused by core (but used by tests)
8987
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8988
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8989
0
{
8990
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8991
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8992
0
    return routing_data->RoutingCurr == routing_id;
8993
0
}
8994
8995
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8996
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8997
bool ImGui::IsKeyDown(ImGuiKey key)
8998
388k
{
8999
388k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9000
388k
}
9001
9002
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9003
433k
{
9004
433k
    const ImGuiKeyData* key_data = GetKeyData(key);
9005
433k
    if (!key_data->Down)
9006
422k
        return false;
9007
11.8k
    if (!TestKeyOwner(key, owner_id))
9008
0
        return false;
9009
11.8k
    return true;
9010
11.8k
}
9011
9012
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9013
259k
{
9014
259k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9015
259k
}
9016
9017
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9018
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9019
487k
{
9020
487k
    const ImGuiKeyData* key_data = GetKeyData(key);
9021
487k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9022
454k
        return false;
9023
33.0k
    const float t = key_data->DownDuration;
9024
33.0k
    if (t < 0.0f)
9025
0
        return false;
9026
33.0k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9027
9028
33.0k
    bool pressed = (t == 0.0f);
9029
33.0k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
9030
31.3k
    {
9031
31.3k
        float repeat_delay, repeat_rate;
9032
31.3k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9033
31.3k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9034
31.3k
    }
9035
33.0k
    if (!pressed)
9036
24.1k
        return false;
9037
8.90k
    if (!TestKeyOwner(key, owner_id))
9038
0
        return false;
9039
8.90k
    return true;
9040
8.90k
}
9041
9042
bool ImGui::IsKeyReleased(ImGuiKey key)
9043
0
{
9044
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9045
0
}
9046
9047
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9048
0
{
9049
0
    const ImGuiKeyData* key_data = GetKeyData(key);
9050
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9051
0
        return false;
9052
0
    if (!TestKeyOwner(key, owner_id))
9053
0
        return false;
9054
0
    return true;
9055
0
}
9056
9057
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9058
0
{
9059
0
    ImGuiContext& g = *GImGui;
9060
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9061
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9062
0
}
9063
9064
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9065
154
{
9066
154
    ImGuiContext& g = *GImGui;
9067
154
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9068
154
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9069
154
}
9070
9071
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9072
0
{
9073
0
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
9074
0
}
9075
9076
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
9077
1.23k
{
9078
1.23k
    ImGuiContext& g = *GImGui;
9079
1.23k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9080
1.23k
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9081
1.08k
        return false;
9082
154
    const float t = g.IO.MouseDownDuration[button];
9083
154
    if (t < 0.0f)
9084
0
        return false;
9085
154
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9086
9087
154
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9088
154
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9089
154
    if (!pressed)
9090
142
        return false;
9091
9092
12
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9093
0
        return false;
9094
9095
12
    return true;
9096
12
}
9097
9098
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9099
0
{
9100
0
    ImGuiContext& g = *GImGui;
9101
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9102
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9103
0
}
9104
9105
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9106
1.23k
{
9107
1.23k
    ImGuiContext& g = *GImGui;
9108
1.23k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9109
1.23k
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9110
1.23k
}
9111
9112
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9113
0
{
9114
0
    ImGuiContext& g = *GImGui;
9115
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9116
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9117
0
}
9118
9119
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9120
0
{
9121
0
    ImGuiContext& g = *GImGui;
9122
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9123
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9124
0
}
9125
9126
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9127
0
{
9128
0
    ImGuiContext& g = *GImGui;
9129
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9130
0
    return g.IO.MouseClickedCount[button];
9131
0
}
9132
9133
// Test if mouse cursor is hovering given rectangle
9134
// NB- Rectangle is clipped by our current clip setting
9135
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9136
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9137
197k
{
9138
197k
    ImGuiContext& g = *GImGui;
9139
9140
    // Clip
9141
197k
    ImRect rect_clipped(r_min, r_max);
9142
197k
    if (clip)
9143
120k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9144
9145
    // Hit testing, expanded for touch input
9146
197k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9147
187k
        return false;
9148
10.2k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9149
0
        return false;
9150
10.2k
    return true;
9151
10.2k
}
9152
9153
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9154
// [Internal] This doesn't test if the button is pressed
9155
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9156
154
{
9157
154
    ImGuiContext& g = *GImGui;
9158
154
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9159
154
    if (lock_threshold < 0.0f)
9160
154
        lock_threshold = g.IO.MouseDragThreshold;
9161
154
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9162
154
}
9163
9164
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9165
154
{
9166
154
    ImGuiContext& g = *GImGui;
9167
154
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9168
154
    if (!g.IO.MouseDown[button])
9169
0
        return false;
9170
154
    return IsMouseDragPastThreshold(button, lock_threshold);
9171
154
}
9172
9173
ImVec2 ImGui::GetMousePos()
9174
5.90k
{
9175
5.90k
    ImGuiContext& g = *GImGui;
9176
5.90k
    return g.IO.MousePos;
9177
5.90k
}
9178
9179
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9180
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9181
void ImGui::TeleportMousePos(const ImVec2& pos)
9182
0
{
9183
0
    ImGuiContext& g = *GImGui;
9184
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9185
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9186
0
    g.IO.WantSetMousePos = true;
9187
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9188
0
}
9189
9190
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9191
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9192
0
{
9193
0
    ImGuiContext& g = *GImGui;
9194
0
    if (g.BeginPopupStack.Size > 0)
9195
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9196
0
    return g.IO.MousePos;
9197
0
}
9198
9199
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9200
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9201
84.8k
{
9202
    // The assert is only to silence a false-positive in XCode Static Analysis.
9203
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9204
84.8k
    IM_ASSERT(GImGui != NULL);
9205
84.8k
    const float MOUSE_INVALID = -256000.0f;
9206
84.8k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9207
84.8k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9208
84.8k
}
9209
9210
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9211
bool ImGui::IsAnyMouseDown()
9212
0
{
9213
0
    ImGuiContext& g = *GImGui;
9214
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9215
0
        if (g.IO.MouseDown[n])
9216
0
            return true;
9217
0
    return false;
9218
0
}
9219
9220
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9221
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9222
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9223
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9224
0
{
9225
0
    ImGuiContext& g = *GImGui;
9226
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9227
0
    if (lock_threshold < 0.0f)
9228
0
        lock_threshold = g.IO.MouseDragThreshold;
9229
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9230
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9231
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9232
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9233
0
    return ImVec2(0.0f, 0.0f);
9234
0
}
9235
9236
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9237
0
{
9238
0
    ImGuiContext& g = *GImGui;
9239
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9240
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9241
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9242
0
}
9243
9244
// Get desired mouse cursor shape.
9245
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9246
// updated during the frame, and locked in EndFrame()/Render().
9247
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9248
ImGuiMouseCursor ImGui::GetMouseCursor()
9249
0
{
9250
0
    ImGuiContext& g = *GImGui;
9251
0
    return g.MouseCursor;
9252
0
}
9253
9254
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9255
0
{
9256
0
    ImGuiContext& g = *GImGui;
9257
0
    g.MouseCursor = cursor_type;
9258
0
}
9259
9260
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9261
180k
{
9262
180k
    IM_ASSERT(ImGui::IsAliasKey(key));
9263
180k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9264
180k
    key_data->Down = v;
9265
180k
    key_data->AnalogValue = analog_value;
9266
180k
}
9267
9268
// [Internal] Do not use directly
9269
static ImGuiKeyChord GetMergedModsFromKeys()
9270
51.5k
{
9271
51.5k
    ImGuiKeyChord mods = 0;
9272
51.5k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9273
51.5k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9274
51.5k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9275
51.5k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9276
51.5k
    return mods;
9277
51.5k
}
9278
9279
static void ImGui::UpdateKeyboardInputs()
9280
25.7k
{
9281
25.7k
    ImGuiContext& g = *GImGui;
9282
25.7k
    ImGuiIO& io = g.IO;
9283
9284
    // Import legacy keys or verify they are not used
9285
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9286
    if (io.BackendUsingLegacyKeyArrays == 0)
9287
    {
9288
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9289
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9290
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9291
    }
9292
    else
9293
    {
9294
        if (g.FrameCount == 0)
9295
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9296
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9297
9298
        // Build reverse KeyMap (Named -> Legacy)
9299
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9300
            if (io.KeyMap[n] != -1)
9301
            {
9302
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9303
                io.KeyMap[io.KeyMap[n]] = n;
9304
            }
9305
9306
        // Import legacy keys into new ones
9307
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9308
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9309
            {
9310
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9311
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9312
                io.KeysData[key].Down = io.KeysDown[n];
9313
                if (key != n)
9314
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9315
                io.BackendUsingLegacyKeyArrays = 1;
9316
            }
9317
        if (io.BackendUsingLegacyKeyArrays == 1)
9318
        {
9319
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9320
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9321
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9322
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9323
        }
9324
    }
9325
9326
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9327
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9328
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9329
    {
9330
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9331
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9332
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9333
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9334
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9335
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9336
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9337
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9338
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9339
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9340
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9341
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9342
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9343
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9344
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9345
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9346
        #undef NAV_MAP_KEY
9347
    }
9348
#endif
9349
#endif
9350
9351
    // Update aliases
9352
154k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9353
128k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9354
25.7k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9355
25.7k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9356
9357
    // Synchronize io.KeyMods and io.KeyXXX values.
9358
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9359
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9360
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9361
25.7k
    io.KeyMods = GetMergedModsFromKeys();
9362
25.7k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9363
25.7k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9364
25.7k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9365
25.7k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9366
9367
    // Clear gamepad data if disabled
9368
25.7k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9369
644k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9370
618k
        {
9371
618k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9372
618k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9373
618k
        }
9374
9375
    // Update keys
9376
3.99M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9377
3.96M
    {
9378
3.96M
        ImGuiKeyData* key_data = &io.KeysData[i];
9379
3.96M
        key_data->DownDurationPrev = key_data->DownDuration;
9380
3.96M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9381
3.96M
    }
9382
9383
    // Update keys/input owner (named keys only): one entry per key
9384
3.99M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9385
3.96M
    {
9386
3.96M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9387
3.96M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9388
3.96M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9389
3.96M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9390
3.94M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9391
3.96M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9392
3.96M
    }
9393
9394
25.7k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9395
25.7k
}
9396
9397
static void ImGui::UpdateMouseInputs()
9398
25.7k
{
9399
25.7k
    ImGuiContext& g = *GImGui;
9400
25.7k
    ImGuiIO& io = g.IO;
9401
9402
    // Mouse Wheel swapping flag
9403
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9404
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9405
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9406
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9407
25.7k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9408
9409
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9410
25.7k
    if (IsMousePosValid(&io.MousePos))
9411
5.90k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9412
9413
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9414
25.7k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9415
5.74k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9416
20.0k
    else
9417
20.0k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9418
9419
    // Update stationary timer.
9420
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9421
25.7k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9422
25.7k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9423
25.7k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9424
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9425
9426
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9427
25.7k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9428
1.09k
        g.NavDisableMouseHover = false;
9429
9430
154k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9431
128k
    {
9432
128k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9433
128k
        io.MouseClickedCount[i] = 0; // Will be filled below
9434
128k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9435
128k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9436
128k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9437
128k
        if (io.MouseClicked[i])
9438
849
        {
9439
849
            bool is_repeated_click = false;
9440
849
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9441
780
            {
9442
780
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9443
780
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9444
760
                    is_repeated_click = true;
9445
780
            }
9446
849
            if (is_repeated_click)
9447
760
                io.MouseClickedLastCount[i]++;
9448
89
            else
9449
89
                io.MouseClickedLastCount[i] = 1;
9450
849
            io.MouseClickedTime[i] = g.Time;
9451
849
            io.MouseClickedPos[i] = io.MousePos;
9452
849
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9453
849
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9454
849
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9455
849
        }
9456
128k
        else if (io.MouseDown[i])
9457
830
        {
9458
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9459
830
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9460
830
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9461
830
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9462
830
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9463
830
        }
9464
9465
        // We provide io.MouseDoubleClicked[] as a legacy service
9466
128k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9467
9468
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9469
128k
        if (io.MouseClicked[i])
9470
849
            g.NavDisableMouseHover = false;
9471
128k
    }
9472
25.7k
}
9473
9474
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9475
0
{
9476
0
    ImGuiContext& g = *GImGui;
9477
0
    if (window)
9478
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9479
0
    else
9480
0
        g.WheelingWindowReleaseTimer = 0.0f;
9481
0
    if (g.WheelingWindow == window)
9482
0
        return;
9483
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9484
0
    g.WheelingWindow = window;
9485
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9486
0
    if (window == NULL)
9487
0
    {
9488
0
        g.WheelingWindowStartFrame = -1;
9489
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9490
0
    }
9491
0
}
9492
9493
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9494
0
{
9495
    // For each axis, find window in the hierarchy that may want to use scrolling
9496
0
    ImGuiContext& g = *GImGui;
9497
0
    ImGuiWindow* windows[2] = { NULL, NULL };
9498
0
    for (int axis = 0; axis < 2; axis++)
9499
0
        if (wheel[axis] != 0.0f)
9500
0
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9501
0
            {
9502
                // Bubble up into parent window if:
9503
                // - a child window doesn't allow any scrolling.
9504
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9505
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9506
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9507
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9508
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9509
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9510
0
                    break; // select this window
9511
0
            }
9512
0
    if (windows[0] == NULL && windows[1] == NULL)
9513
0
        return NULL;
9514
9515
    // If there's only one window or only one axis then there's no ambiguity
9516
0
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9517
0
        return windows[1] ? windows[1] : windows[0];
9518
9519
    // If candidate are different windows we need to decide which one to prioritize
9520
    // - First frame: only find a winner if one axis is zero.
9521
    // - Subsequent frames: only find a winner when one is more than the other.
9522
0
    if (g.WheelingWindowStartFrame == -1)
9523
0
        g.WheelingWindowStartFrame = g.FrameCount;
9524
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9525
0
    {
9526
0
        g.WheelingWindowWheelRemainder = wheel;
9527
0
        return NULL;
9528
0
    }
9529
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9530
0
}
9531
9532
// Called by NewFrame()
9533
void ImGui::UpdateMouseWheel()
9534
25.7k
{
9535
    // Reset the locked window if we move the mouse or after the timer elapses.
9536
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9537
25.7k
    ImGuiContext& g = *GImGui;
9538
25.7k
    if (g.WheelingWindow != NULL)
9539
0
    {
9540
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9541
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9542
0
            g.WheelingWindowReleaseTimer = 0.0f;
9543
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9544
0
            LockWheelingWindow(NULL, 0.0f);
9545
0
    }
9546
9547
25.7k
    ImVec2 wheel;
9548
25.7k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9549
25.7k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9550
9551
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9552
25.7k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9553
25.7k
    if (!mouse_window || mouse_window->Collapsed)
9554
23.4k
        return;
9555
9556
    // Zoom / Scale window
9557
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9558
2.30k
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9559
0
    {
9560
0
        LockWheelingWindow(mouse_window, wheel.y);
9561
0
        ImGuiWindow* window = mouse_window;
9562
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9563
0
        const float scale = new_font_scale / window->FontWindowScale;
9564
0
        window->FontWindowScale = new_font_scale;
9565
0
        if (window == window->RootWindow)
9566
0
        {
9567
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9568
0
            SetWindowPos(window, window->Pos + offset, 0);
9569
0
            window->Size = ImTrunc(window->Size * scale);
9570
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
9571
0
        }
9572
0
        return;
9573
0
    }
9574
2.30k
    if (g.IO.KeyCtrl)
9575
0
        return;
9576
9577
    // Mouse wheel scrolling
9578
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9579
2.30k
    if (g.IO.MouseWheelRequestAxisSwap)
9580
0
        wheel = ImVec2(wheel.y, 0.0f);
9581
9582
    // Maintain a rough average of moving magnitude on both axises
9583
    // FIXME: should by based on wall clock time rather than frame-counter
9584
2.30k
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9585
2.30k
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9586
9587
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9588
2.30k
    wheel += g.WheelingWindowWheelRemainder;
9589
2.30k
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9590
2.30k
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9591
2.30k
        return;
9592
9593
    // Mouse wheel scrolling: find target and apply
9594
    // - don't renew lock if axis doesn't apply on the window.
9595
    // - select a main axis when both axises are being moved.
9596
0
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9597
0
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9598
0
        {
9599
0
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9600
0
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9601
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9602
0
            if (do_scroll[ImGuiAxis_X])
9603
0
            {
9604
0
                LockWheelingWindow(window, wheel.x);
9605
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9606
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
9607
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9608
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
9609
0
            }
9610
0
            if (do_scroll[ImGuiAxis_Y])
9611
0
            {
9612
0
                LockWheelingWindow(window, wheel.y);
9613
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9614
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
9615
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9616
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
9617
0
            }
9618
0
        }
9619
0
}
9620
9621
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9622
0
{
9623
0
    ImGuiContext& g = *GImGui;
9624
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9625
0
}
9626
9627
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9628
0
{
9629
0
    ImGuiContext& g = *GImGui;
9630
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9631
0
}
9632
9633
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9634
static const char* GetInputSourceName(ImGuiInputSource source)
9635
0
{
9636
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9637
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9638
0
    return input_source_names[source];
9639
0
}
9640
static const char* GetMouseSourceName(ImGuiMouseSource source)
9641
0
{
9642
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9643
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9644
0
    return mouse_source_names[source];
9645
0
}
9646
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9647
0
{
9648
0
    ImGuiContext& g = *GImGui;
9649
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
9650
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
9651
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9652
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9653
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9654
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9655
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9656
0
}
9657
#endif
9658
9659
// Process input queue
9660
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9661
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9662
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9663
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9664
25.7k
{
9665
25.7k
    ImGuiContext& g = *GImGui;
9666
25.7k
    ImGuiIO& io = g.IO;
9667
9668
    // Only trickle chars<>key when working with InputText()
9669
    // FIXME: InputText() could parse event trail?
9670
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9671
25.7k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9672
9673
25.7k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9674
25.7k
    int  mouse_button_changed = 0x00;
9675
25.7k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9676
9677
25.7k
    int event_n = 0;
9678
31.2k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9679
7.30k
    {
9680
7.30k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9681
7.30k
        if (e->Type == ImGuiInputEventType_MousePos)
9682
1.76k
        {
9683
1.76k
            if (g.IO.WantSetMousePos)
9684
0
                continue;
9685
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9686
1.76k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9687
1.76k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9688
170
                break;
9689
1.59k
            io.MousePos = event_pos;
9690
1.59k
            io.MouseSource = e->MousePos.MouseSource;
9691
1.59k
            mouse_moved = true;
9692
1.59k
        }
9693
5.53k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9694
2.74k
        {
9695
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9696
2.74k
            const ImGuiMouseButton button = e->MouseButton.Button;
9697
2.74k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9698
2.74k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9699
1.13k
                break;
9700
1.61k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9701
0
                break;
9702
1.61k
            io.MouseDown[button] = e->MouseButton.Down;
9703
1.61k
            io.MouseSource = e->MouseButton.MouseSource;
9704
1.61k
            mouse_button_changed |= (1 << button);
9705
1.61k
        }
9706
2.79k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9707
394
        {
9708
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9709
394
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9710
87
                break;
9711
307
            io.MouseWheelH += e->MouseWheel.WheelX;
9712
307
            io.MouseWheel += e->MouseWheel.WheelY;
9713
307
            io.MouseSource = e->MouseWheel.MouseSource;
9714
307
            mouse_wheeled = true;
9715
307
        }
9716
2.39k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9717
0
        {
9718
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9719
0
        }
9720
2.39k
        else if (e->Type == ImGuiInputEventType_Key)
9721
897
        {
9722
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9723
897
            ImGuiKey key = e->Key.Key;
9724
897
            IM_ASSERT(key != ImGuiKey_None);
9725
897
            ImGuiKeyData* key_data = GetKeyData(key);
9726
897
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9727
897
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9728
145
                break;
9729
752
            key_data->Down = e->Key.Down;
9730
752
            key_data->AnalogValue = e->Key.AnalogValue;
9731
752
            key_changed = true;
9732
752
            key_changed_mask.SetBit(key_data_index);
9733
9734
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9735
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9736
            io.KeysDown[key_data_index] = key_data->Down;
9737
            if (io.KeyMap[key_data_index] != -1)
9738
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9739
#endif
9740
752
        }
9741
1.49k
        else if (e->Type == ImGuiInputEventType_Text)
9742
1.20k
        {
9743
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9744
1.20k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9745
300
                break;
9746
909
            unsigned int c = e->Text.Char;
9747
909
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9748
909
            if (trickle_interleaved_keys_and_text)
9749
0
                text_inputted = true;
9750
909
        }
9751
290
        else if (e->Type == ImGuiInputEventType_Focus)
9752
290
        {
9753
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9754
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9755
290
            const bool focus_lost = !e->AppFocused.Focused;
9756
290
            io.AppFocusLost = focus_lost;
9757
290
        }
9758
0
        else
9759
0
        {
9760
0
            IM_ASSERT(0 && "Unknown event!");
9761
0
        }
9762
7.30k
    }
9763
9764
    // Record trail (for domain-specific applications wanting to access a precise trail)
9765
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9766
31.2k
    for (int n = 0; n < event_n; n++)
9767
5.46k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9768
9769
    // [DEBUG]
9770
25.7k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9771
25.7k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9772
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9773
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9774
25.7k
#endif
9775
9776
    // Remaining events will be processed on the next frame
9777
25.7k
    if (event_n == g.InputEventsQueue.Size)
9778
23.9k
        g.InputEventsQueue.resize(0);
9779
1.83k
    else
9780
1.83k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9781
9782
    // Clear buttons state when focus is lost
9783
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9784
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9785
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9786
25.7k
    if (g.IO.AppFocusLost)
9787
290
        g.IO.ClearInputKeys();
9788
25.7k
}
9789
9790
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9791
0
{
9792
0
    if (!IsNamedKeyOrModKey(key))
9793
0
        return ImGuiKeyOwner_None;
9794
9795
0
    ImGuiContext& g = *GImGui;
9796
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9797
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9798
9799
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9800
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9801
0
            return ImGuiKeyOwner_None;
9802
9803
0
    return owner_id;
9804
0
}
9805
9806
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9807
// TestKeyOwner(..., None) : (owner == None)
9808
// TestKeyOwner(..., Any)  : no owner test
9809
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9810
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9811
72.4k
{
9812
72.4k
    if (!IsNamedKeyOrModKey(key))
9813
0
        return true;
9814
9815
72.4k
    ImGuiContext& g = *GImGui;
9816
72.4k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9817
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9818
0
            return false;
9819
9820
72.4k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9821
72.4k
    if (owner_id == ImGuiKeyOwner_Any)
9822
7.06k
        return (owner_data->LockThisFrame == false);
9823
9824
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9825
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9826
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9827
65.4k
    if (owner_data->OwnerCurr != owner_id)
9828
12
    {
9829
12
        if (owner_data->LockThisFrame)
9830
0
            return false;
9831
12
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9832
0
            return false;
9833
12
    }
9834
9835
65.4k
    return true;
9836
65.4k
}
9837
9838
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9839
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9840
// - SetKeyOwner(..., None)              : clears owner
9841
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9842
// - SetKeyOwner(..., Any or None, Lock) : set lock
9843
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9844
12
{
9845
12
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9846
12
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9847
9848
12
    ImGuiContext& g = *GImGui;
9849
12
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9850
12
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9851
9852
    // We cannot lock by default as it would likely break lots of legacy code.
9853
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9854
12
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9855
12
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9856
12
}
9857
9858
// Rarely used helper
9859
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9860
0
{
9861
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9862
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9863
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9864
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9865
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9866
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9867
0
}
9868
9869
// This is more or less equivalent to:
9870
//   if (IsItemHovered() || IsItemActive())
9871
//       SetKeyOwner(key, GetItemID());
9872
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9873
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9874
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9875
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9876
0
{
9877
0
    ImGuiContext& g = *GImGui;
9878
0
    ImGuiID id = g.LastItemData.ID;
9879
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9880
0
        return;
9881
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9882
0
        flags |= ImGuiInputFlags_CondDefault_;
9883
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9884
0
    {
9885
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9886
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9887
0
    }
9888
0
}
9889
9890
// This is the only public API until we expose owner_id versions of the API as replacements.
9891
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
9892
0
{
9893
0
    return IsKeyChordPressed(key_chord, 0, ImGuiInputFlags_None);
9894
0
}
9895
9896
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
9897
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9898
51.5k
{
9899
51.5k
    ImGuiContext& g = *GImGui;
9900
51.5k
    if (key_chord & ImGuiMod_Shortcut)
9901
0
        key_chord = ConvertShortcutMod(key_chord);
9902
51.5k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9903
51.5k
    if (g.IO.KeyMods != mods)
9904
51.5k
        return false;
9905
9906
    // Special storage location for mods
9907
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9908
0
    if (key == ImGuiKey_None)
9909
0
        key = ConvertSingleModFlagToKey(&g, mods);
9910
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9911
0
        return false;
9912
0
    return true;
9913
0
}
9914
9915
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9916
51.5k
{
9917
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9918
51.5k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9919
51.5k
        flags |= ImGuiInputFlags_RouteFocused;
9920
51.5k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9921
0
        return false;
9922
9923
51.5k
    if (!IsKeyChordPressed(key_chord, owner_id, flags))
9924
51.5k
        return false;
9925
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9926
0
    return true;
9927
51.5k
}
9928
9929
9930
//-----------------------------------------------------------------------------
9931
// [SECTION] ERROR CHECKING
9932
//-----------------------------------------------------------------------------
9933
9934
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9935
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9936
// If this triggers you have an issue:
9937
// - Most commonly: mismatched headers and compiled code version.
9938
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9939
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9940
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9941
//   Otherwise it is possible that different compilation units would see different structure layout
9942
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9943
1
{
9944
1
    bool error = false;
9945
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9946
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9947
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9948
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9949
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9950
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9951
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9952
1
    return !error;
9953
1
}
9954
9955
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9956
// This is causing issues and ambiguity and we need to retire that.
9957
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9958
// [Scenario 1]
9959
//  Previously this would make the window content size ~200x200:
9960
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9961
//  Instead, please submit an item:
9962
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9963
//  Alternative:
9964
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9965
// [Scenario 2]
9966
//  For reference this is one of the issue what we aim to fix with this change:
9967
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9968
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9969
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9970
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9971
0
{
9972
0
    ImGuiContext& g = *GImGui;
9973
0
    ImGuiWindow* window = g.CurrentWindow;
9974
0
    IM_ASSERT(window->DC.IsSetPos);
9975
0
    window->DC.IsSetPos = false;
9976
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9977
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9978
0
        return;
9979
0
    if (window->SkipItems)
9980
0
        return;
9981
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9982
#else
9983
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9984
#endif
9985
0
}
9986
9987
static void ImGui::ErrorCheckNewFrameSanityChecks()
9988
25.7k
{
9989
25.7k
    ImGuiContext& g = *GImGui;
9990
9991
    // Check user IM_ASSERT macro
9992
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9993
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9994
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9995
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9996
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9997
25.7k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9998
9999
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10000
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10001
#ifdef __EMSCRIPTEN__
10002
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10003
        g.IO.DeltaTime = 0.00001f;
10004
#endif
10005
10006
    // Check user data
10007
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10008
25.7k
    IM_ASSERT(g.Initialized);
10009
25.7k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10010
25.7k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10011
25.7k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10012
25.7k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10013
25.7k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10014
25.7k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10015
25.7k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10016
25.7k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10017
25.7k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10018
25.7k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10019
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10020
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10021
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10022
10023
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10024
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10025
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10026
#endif
10027
10028
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
10029
25.7k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
10030
1
        g.IO.ConfigWindowsResizeFromEdges = false;
10031
10032
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10033
25.7k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10034
25.7k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10035
25.7k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10036
25.7k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10037
10038
    // Perform simple checks: multi-viewport and platform windows support
10039
25.7k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10040
1
    {
10041
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10042
0
        {
10043
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10044
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10045
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10046
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10047
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10048
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10049
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10050
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10051
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10052
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10053
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10054
0
        }
10055
1
        else
10056
1
        {
10057
            // Disable feature, our backends do not support it
10058
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10059
1
        }
10060
10061
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10062
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10063
0
        {
10064
0
            IM_UNUSED(mon);
10065
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10066
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10067
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10068
0
        }
10069
1
    }
10070
25.7k
}
10071
10072
static void ImGui::ErrorCheckEndFrameSanityChecks()
10073
25.7k
{
10074
25.7k
    ImGuiContext& g = *GImGui;
10075
10076
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10077
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10078
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10079
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10080
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10081
    // while still correctly asserting on mid-frame key press events.
10082
25.7k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10083
25.7k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10084
25.7k
    IM_UNUSED(key_mods);
10085
10086
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10087
    //ErrorCheckEndFrameRecover();
10088
10089
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10090
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10091
25.7k
    if (g.CurrentWindowStack.Size != 1)
10092
0
    {
10093
0
        if (g.CurrentWindowStack.Size > 1)
10094
0
        {
10095
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10096
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10097
0
            IM_UNUSED(window);
10098
0
            while (g.CurrentWindowStack.Size > 1)
10099
0
                End();
10100
0
        }
10101
0
        else
10102
0
        {
10103
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10104
0
        }
10105
0
    }
10106
10107
25.7k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10108
25.7k
}
10109
10110
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10111
// Must be called during or before EndFrame().
10112
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10113
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10114
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10115
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10116
0
{
10117
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10118
0
    ImGuiContext& g = *GImGui;
10119
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10120
0
    {
10121
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10122
0
        ImGuiWindow* window = g.CurrentWindow;
10123
0
        if (g.CurrentWindowStack.Size == 1)
10124
0
        {
10125
0
            IM_ASSERT(window->IsFallbackWindow);
10126
0
            break;
10127
0
        }
10128
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10129
0
        {
10130
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10131
0
            EndChild();
10132
0
        }
10133
0
        else
10134
0
        {
10135
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10136
0
            End();
10137
0
        }
10138
0
    }
10139
0
}
10140
10141
// Must be called before End()/EndChild()
10142
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10143
0
{
10144
0
    ImGuiContext& g = *GImGui;
10145
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10146
0
    {
10147
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10148
0
        EndTable();
10149
0
    }
10150
10151
0
    ImGuiWindow* window = g.CurrentWindow;
10152
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10153
0
    IM_ASSERT(window != NULL);
10154
0
    while (g.CurrentTabBar != NULL) //-V1044
10155
0
    {
10156
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10157
0
        EndTabBar();
10158
0
    }
10159
0
    while (window->DC.TreeDepth > 0)
10160
0
    {
10161
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10162
0
        TreePop();
10163
0
    }
10164
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10165
0
    {
10166
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10167
0
        EndGroup();
10168
0
    }
10169
0
    while (window->IDStack.Size > 1)
10170
0
    {
10171
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10172
0
        PopID();
10173
0
    }
10174
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10175
0
    {
10176
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10177
0
        EndDisabled();
10178
0
    }
10179
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10180
0
    {
10181
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10182
0
        PopStyleColor();
10183
0
    }
10184
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10185
0
    {
10186
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10187
0
        PopItemFlag();
10188
0
    }
10189
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10190
0
    {
10191
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10192
0
        PopStyleVar();
10193
0
    }
10194
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10195
0
    {
10196
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10197
0
        PopFont();
10198
0
    }
10199
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10200
0
    {
10201
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10202
0
        PopFocusScope();
10203
0
    }
10204
0
}
10205
10206
// Save current stack sizes for later compare
10207
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10208
77.3k
{
10209
77.3k
    ImGuiContext& g = *ctx;
10210
77.3k
    ImGuiWindow* window = g.CurrentWindow;
10211
77.3k
    SizeOfIDStack = (short)window->IDStack.Size;
10212
77.3k
    SizeOfColorStack = (short)g.ColorStack.Size;
10213
77.3k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10214
77.3k
    SizeOfFontStack = (short)g.FontStack.Size;
10215
77.3k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10216
77.3k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10217
77.3k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10218
77.3k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10219
77.3k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10220
77.3k
}
10221
10222
// Compare to detect usage errors
10223
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10224
77.3k
{
10225
77.3k
    ImGuiContext& g = *ctx;
10226
77.3k
    ImGuiWindow* window = g.CurrentWindow;
10227
77.3k
    IM_UNUSED(window);
10228
10229
    // Window stacks
10230
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10231
77.3k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10232
10233
    // Global stacks
10234
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10235
77.3k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10236
77.3k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10237
77.3k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10238
77.3k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10239
77.3k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10240
77.3k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10241
77.3k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10242
77.3k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10243
77.3k
}
10244
10245
10246
//-----------------------------------------------------------------------------
10247
// [SECTION] LAYOUT
10248
//-----------------------------------------------------------------------------
10249
// - ItemSize()
10250
// - ItemAdd()
10251
// - SameLine()
10252
// - GetCursorScreenPos()
10253
// - SetCursorScreenPos()
10254
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10255
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10256
// - GetCursorStartPos()
10257
// - Indent()
10258
// - Unindent()
10259
// - SetNextItemWidth()
10260
// - PushItemWidth()
10261
// - PushMultiItemsWidths()
10262
// - PopItemWidth()
10263
// - CalcItemWidth()
10264
// - CalcItemSize()
10265
// - GetTextLineHeight()
10266
// - GetTextLineHeightWithSpacing()
10267
// - GetFrameHeight()
10268
// - GetFrameHeightWithSpacing()
10269
// - GetContentRegionMax()
10270
// - GetContentRegionMaxAbs() [Internal]
10271
// - GetContentRegionAvail(),
10272
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10273
// - BeginGroup()
10274
// - EndGroup()
10275
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10276
//-----------------------------------------------------------------------------
10277
10278
// Advance cursor given item size for layout.
10279
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10280
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10281
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10282
51.5k
{
10283
51.5k
    ImGuiContext& g = *GImGui;
10284
51.5k
    ImGuiWindow* window = g.CurrentWindow;
10285
51.5k
    if (window->SkipItems)
10286
0
        return;
10287
10288
    // We increase the height in this function to accommodate for baseline offset.
10289
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10290
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10291
51.5k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10292
10293
51.5k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10294
51.5k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10295
10296
    // Always align ourselves on pixel boundaries
10297
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10298
51.5k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10299
51.5k
    window->DC.CursorPosPrevLine.y = line_y1;
10300
51.5k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10301
51.5k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10302
51.5k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10303
51.5k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10304
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10305
10306
51.5k
    window->DC.PrevLineSize.y = line_height;
10307
51.5k
    window->DC.CurrLineSize.y = 0.0f;
10308
51.5k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10309
51.5k
    window->DC.CurrLineTextBaseOffset = 0.0f;
10310
51.5k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10311
10312
    // Horizontal layout mode
10313
51.5k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10314
0
        SameLine();
10315
51.5k
}
10316
10317
// Declare item bounding box for clipping and interaction.
10318
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10319
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10320
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10321
136k
{
10322
136k
    ImGuiContext& g = *GImGui;
10323
136k
    ImGuiWindow* window = g.CurrentWindow;
10324
10325
    // Set item data
10326
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10327
136k
    g.LastItemData.ID = id;
10328
136k
    g.LastItemData.Rect = bb;
10329
136k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10330
136k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10331
136k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10332
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10333
10334
    // Directional navigation processing
10335
136k
    if (id != 0)
10336
109k
    {
10337
109k
        KeepAliveID(id);
10338
10339
        // Runs prior to clipping early-out
10340
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10341
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10342
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10343
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10344
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10345
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10346
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10347
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10348
109k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10349
76.2k
        {
10350
76.2k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10351
76.2k
            if (g.NavId == id || g.NavAnyRequest)
10352
8.06k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10353
1.07k
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10354
1.07k
                        NavProcessItem();
10355
76.2k
        }
10356
10357
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10358
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10359
        // READ THE FAQ: https://dearimgui.com/faq
10360
109k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10361
109k
    }
10362
136k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10363
136k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10364
10365
#ifdef IMGUI_ENABLE_TEST_ENGINE
10366
    if (id != 0)
10367
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10368
#endif
10369
10370
    // Clipping test
10371
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10372
    //const bool is_clipped = IsClippedEx(bb, id);
10373
    //if (is_clipped)
10374
    //    return false;
10375
136k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10376
136k
    if (!is_rect_visible)
10377
22.9k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
10378
22.9k
            if (!g.LogEnabled)
10379
22.9k
                return false;
10380
10381
    // [DEBUG]
10382
113k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10383
113k
    if (id != 0 && id == g.DebugLocateId)
10384
0
        DebugLocateItemResolveWithLastItem();
10385
113k
#endif
10386
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10387
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10388
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10389
10390
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10391
113k
    if (is_rect_visible)
10392
113k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10393
113k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10394
2.80k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10395
113k
    return true;
10396
136k
}
10397
10398
// Gets back to previous line and continue with horizontal layout
10399
//      offset_from_start_x == 0 : follow right after previous item
10400
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10401
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
10402
//      spacing_w >= 0           : enforce spacing amount
10403
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10404
0
{
10405
0
    ImGuiContext& g = *GImGui;
10406
0
    ImGuiWindow* window = g.CurrentWindow;
10407
0
    if (window->SkipItems)
10408
0
        return;
10409
10410
0
    if (offset_from_start_x != 0.0f)
10411
0
    {
10412
0
        if (spacing_w < 0.0f)
10413
0
            spacing_w = 0.0f;
10414
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10415
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10416
0
    }
10417
0
    else
10418
0
    {
10419
0
        if (spacing_w < 0.0f)
10420
0
            spacing_w = g.Style.ItemSpacing.x;
10421
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10422
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10423
0
    }
10424
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10425
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10426
0
    window->DC.IsSameLine = true;
10427
0
}
10428
10429
ImVec2 ImGui::GetCursorScreenPos()
10430
31.6k
{
10431
31.6k
    ImGuiWindow* window = GetCurrentWindowRead();
10432
31.6k
    return window->DC.CursorPos;
10433
31.6k
}
10434
10435
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10436
0
{
10437
0
    ImGuiWindow* window = GetCurrentWindow();
10438
0
    window->DC.CursorPos = pos;
10439
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10440
0
    window->DC.IsSetPos = true;
10441
0
}
10442
10443
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10444
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10445
ImVec2 ImGui::GetCursorPos()
10446
0
{
10447
0
    ImGuiWindow* window = GetCurrentWindowRead();
10448
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10449
0
}
10450
10451
float ImGui::GetCursorPosX()
10452
0
{
10453
0
    ImGuiWindow* window = GetCurrentWindowRead();
10454
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10455
0
}
10456
10457
float ImGui::GetCursorPosY()
10458
0
{
10459
0
    ImGuiWindow* window = GetCurrentWindowRead();
10460
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10461
0
}
10462
10463
void ImGui::SetCursorPos(const ImVec2& local_pos)
10464
0
{
10465
0
    ImGuiWindow* window = GetCurrentWindow();
10466
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10467
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10468
0
    window->DC.IsSetPos = true;
10469
0
}
10470
10471
void ImGui::SetCursorPosX(float x)
10472
0
{
10473
0
    ImGuiWindow* window = GetCurrentWindow();
10474
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10475
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10476
0
    window->DC.IsSetPos = true;
10477
0
}
10478
10479
void ImGui::SetCursorPosY(float y)
10480
0
{
10481
0
    ImGuiWindow* window = GetCurrentWindow();
10482
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10483
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10484
0
    window->DC.IsSetPos = true;
10485
0
}
10486
10487
ImVec2 ImGui::GetCursorStartPos()
10488
0
{
10489
0
    ImGuiWindow* window = GetCurrentWindowRead();
10490
0
    return window->DC.CursorStartPos - window->Pos;
10491
0
}
10492
10493
void ImGui::Indent(float indent_w)
10494
0
{
10495
0
    ImGuiContext& g = *GImGui;
10496
0
    ImGuiWindow* window = GetCurrentWindow();
10497
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10498
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10499
0
}
10500
10501
void ImGui::Unindent(float indent_w)
10502
0
{
10503
0
    ImGuiContext& g = *GImGui;
10504
0
    ImGuiWindow* window = GetCurrentWindow();
10505
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10506
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10507
0
}
10508
10509
// Affect large frame+labels widgets only.
10510
void ImGui::SetNextItemWidth(float item_width)
10511
0
{
10512
0
    ImGuiContext& g = *GImGui;
10513
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10514
0
    g.NextItemData.Width = item_width;
10515
0
}
10516
10517
// FIXME: Remove the == 0.0f behavior?
10518
void ImGui::PushItemWidth(float item_width)
10519
0
{
10520
0
    ImGuiContext& g = *GImGui;
10521
0
    ImGuiWindow* window = g.CurrentWindow;
10522
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10523
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10524
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10525
0
}
10526
10527
void ImGui::PushMultiItemsWidths(int components, float w_full)
10528
0
{
10529
0
    ImGuiContext& g = *GImGui;
10530
0
    ImGuiWindow* window = g.CurrentWindow;
10531
0
    const ImGuiStyle& style = g.Style;
10532
0
    const float w_item_one  = ImMax(1.0f, IM_TRUNC((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10533
0
    const float w_item_last = ImMax(1.0f, IM_TRUNC(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10534
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10535
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10536
0
    for (int i = 0; i < components - 2; i++)
10537
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10538
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10539
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10540
0
}
10541
10542
void ImGui::PopItemWidth()
10543
0
{
10544
0
    ImGuiWindow* window = GetCurrentWindow();
10545
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10546
0
    window->DC.ItemWidthStack.pop_back();
10547
0
}
10548
10549
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10550
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10551
float ImGui::CalcItemWidth()
10552
0
{
10553
0
    ImGuiContext& g = *GImGui;
10554
0
    ImGuiWindow* window = g.CurrentWindow;
10555
0
    float w;
10556
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10557
0
        w = g.NextItemData.Width;
10558
0
    else
10559
0
        w = window->DC.ItemWidth;
10560
0
    if (w < 0.0f)
10561
0
    {
10562
0
        float region_max_x = GetContentRegionMaxAbs().x;
10563
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10564
0
    }
10565
0
    w = IM_TRUNC(w);
10566
0
    return w;
10567
0
}
10568
10569
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10570
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10571
// Note that only CalcItemWidth() is publicly exposed.
10572
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10573
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10574
25.7k
{
10575
25.7k
    ImGuiContext& g = *GImGui;
10576
25.7k
    ImGuiWindow* window = g.CurrentWindow;
10577
10578
25.7k
    ImVec2 region_max;
10579
25.7k
    if (size.x < 0.0f || size.y < 0.0f)
10580
0
        region_max = GetContentRegionMaxAbs();
10581
10582
25.7k
    if (size.x == 0.0f)
10583
3.90k
        size.x = default_w;
10584
21.8k
    else if (size.x < 0.0f)
10585
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10586
10587
25.7k
    if (size.y == 0.0f)
10588
1.57k
        size.y = default_h;
10589
24.2k
    else if (size.y < 0.0f)
10590
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10591
10592
25.7k
    return size;
10593
25.7k
}
10594
10595
float ImGui::GetTextLineHeight()
10596
0
{
10597
0
    ImGuiContext& g = *GImGui;
10598
0
    return g.FontSize;
10599
0
}
10600
10601
float ImGui::GetTextLineHeightWithSpacing()
10602
25.7k
{
10603
25.7k
    ImGuiContext& g = *GImGui;
10604
25.7k
    return g.FontSize + g.Style.ItemSpacing.y;
10605
25.7k
}
10606
10607
float ImGui::GetFrameHeight()
10608
0
{
10609
0
    ImGuiContext& g = *GImGui;
10610
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10611
0
}
10612
10613
float ImGui::GetFrameHeightWithSpacing()
10614
0
{
10615
0
    ImGuiContext& g = *GImGui;
10616
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10617
0
}
10618
10619
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10620
10621
// FIXME: This is in window space (not screen space!).
10622
ImVec2 ImGui::GetContentRegionMax()
10623
0
{
10624
0
    ImGuiContext& g = *GImGui;
10625
0
    ImGuiWindow* window = g.CurrentWindow;
10626
0
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10627
0
    return mx - window->Pos;
10628
0
}
10629
10630
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10631
ImVec2 ImGui::GetContentRegionMaxAbs()
10632
25.7k
{
10633
25.7k
    ImGuiContext& g = *GImGui;
10634
25.7k
    ImGuiWindow* window = g.CurrentWindow;
10635
25.7k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
10636
25.7k
    return mx;
10637
25.7k
}
10638
10639
ImVec2 ImGui::GetContentRegionAvail()
10640
25.7k
{
10641
25.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
10642
25.7k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10643
25.7k
}
10644
10645
// In window space (not screen space!)
10646
ImVec2 ImGui::GetWindowContentRegionMin()
10647
0
{
10648
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10649
0
    return window->ContentRegionRect.Min - window->Pos;
10650
0
}
10651
10652
ImVec2 ImGui::GetWindowContentRegionMax()
10653
25.7k
{
10654
25.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
10655
25.7k
    return window->ContentRegionRect.Max - window->Pos;
10656
25.7k
}
10657
10658
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10659
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10660
// FIXME-OPT: Could we safely early out on ->SkipItems?
10661
void ImGui::BeginGroup()
10662
0
{
10663
0
    ImGuiContext& g = *GImGui;
10664
0
    ImGuiWindow* window = g.CurrentWindow;
10665
10666
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10667
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10668
0
    group_data.WindowID = window->ID;
10669
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10670
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
10671
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10672
0
    group_data.BackupIndent = window->DC.Indent;
10673
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10674
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10675
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10676
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10677
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10678
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
10679
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10680
0
    group_data.EmitItem = true;
10681
10682
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10683
0
    window->DC.Indent = window->DC.GroupOffset;
10684
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10685
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10686
0
    if (g.LogEnabled)
10687
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10688
0
}
10689
10690
void ImGui::EndGroup()
10691
0
{
10692
0
    ImGuiContext& g = *GImGui;
10693
0
    ImGuiWindow* window = g.CurrentWindow;
10694
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10695
10696
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10697
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10698
10699
0
    if (window->DC.IsSetPos)
10700
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10701
10702
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10703
10704
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10705
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
10706
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10707
0
    window->DC.Indent = group_data.BackupIndent;
10708
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10709
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10710
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10711
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
10712
0
    if (g.LogEnabled)
10713
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10714
10715
0
    if (!group_data.EmitItem)
10716
0
    {
10717
0
        g.GroupStack.pop_back();
10718
0
        return;
10719
0
    }
10720
10721
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10722
0
    ItemSize(group_bb.GetSize());
10723
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10724
10725
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10726
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10727
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10728
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10729
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10730
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10731
0
    if (group_contains_curr_active_id)
10732
0
        g.LastItemData.ID = g.ActiveId;
10733
0
    else if (group_contains_prev_active_id)
10734
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10735
0
    g.LastItemData.Rect = group_bb;
10736
10737
    // Forward Hovered flag
10738
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10739
0
    if (group_contains_curr_hovered_id)
10740
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10741
10742
    // Forward Edited flag
10743
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10744
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10745
10746
    // Forward Deactivated flag
10747
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10748
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10749
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10750
10751
0
    g.GroupStack.pop_back();
10752
0
    if (g.DebugShowGroupRects)
10753
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10754
0
}
10755
10756
10757
//-----------------------------------------------------------------------------
10758
// [SECTION] SCROLLING
10759
//-----------------------------------------------------------------------------
10760
10761
// Helper to snap on edges when aiming at an item very close to the edge,
10762
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10763
// When we refactor the scrolling API this may be configurable with a flag?
10764
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10765
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10766
0
{
10767
0
    if (target <= snap_min + snap_threshold)
10768
0
        return ImLerp(snap_min, target, center_ratio);
10769
0
    if (target >= snap_max - snap_threshold)
10770
0
        return ImLerp(target, snap_max, center_ratio);
10771
0
    return target;
10772
0
}
10773
10774
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10775
77.4k
{
10776
77.4k
    ImVec2 scroll = window->Scroll;
10777
77.4k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10778
232k
    for (int axis = 0; axis < 2; axis++)
10779
154k
    {
10780
154k
        if (window->ScrollTarget[axis] < FLT_MAX)
10781
18.9k
        {
10782
18.9k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10783
18.9k
            float scroll_target = window->ScrollTarget[axis];
10784
18.9k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10785
0
            {
10786
0
                float snap_min = 0.0f;
10787
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10788
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10789
0
            }
10790
18.9k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10791
18.9k
        }
10792
154k
        scroll[axis] = IM_TRUNC(ImMax(scroll[axis], 0.0f));
10793
154k
        if (!window->Collapsed && !window->SkipItems)
10794
154k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10795
154k
    }
10796
77.4k
    return scroll;
10797
77.4k
}
10798
10799
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10800
0
{
10801
0
    ImGuiContext& g = *GImGui;
10802
0
    ImGuiWindow* window = g.CurrentWindow;
10803
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10804
0
}
10805
10806
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10807
0
{
10808
0
    ScrollToRectEx(window, item_rect, flags);
10809
0
}
10810
10811
// Scroll to keep newly navigated item fully into view
10812
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10813
171
{
10814
171
    ImGuiContext& g = *GImGui;
10815
171
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10816
171
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10817
171
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10818
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10819
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10820
10821
    // Check that only one behavior is selected per axis
10822
171
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10823
171
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10824
10825
    // Defaults
10826
171
    ImGuiScrollFlags in_flags = flags;
10827
171
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10828
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10829
171
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10830
10
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10831
10832
171
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10833
171
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10834
171
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10835
171
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10836
10837
171
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10838
0
    {
10839
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10840
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10841
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10842
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10843
0
    }
10844
171
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10845
0
    {
10846
0
        if (can_be_fully_visible_x)
10847
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10848
0
        else
10849
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10850
0
    }
10851
10852
171
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10853
0
    {
10854
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10855
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10856
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10857
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10858
0
    }
10859
171
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10860
0
    {
10861
0
        if (can_be_fully_visible_y)
10862
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10863
0
        else
10864
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10865
0
    }
10866
10867
171
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10868
171
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10869
10870
    // Also scroll parent window to keep us into view if necessary
10871
171
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10872
0
    {
10873
        // FIXME-SCROLL: May be an option?
10874
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10875
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10876
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10877
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10878
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10879
0
    }
10880
10881
171
    return delta_scroll;
10882
171
}
10883
10884
float ImGui::GetScrollX()
10885
34.7k
{
10886
34.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
10887
34.7k
    return window->Scroll.x;
10888
34.7k
}
10889
10890
float ImGui::GetScrollY()
10891
34.7k
{
10892
34.7k
    ImGuiWindow* window = GImGui->CurrentWindow;
10893
34.7k
    return window->Scroll.y;
10894
34.7k
}
10895
10896
float ImGui::GetScrollMaxX()
10897
0
{
10898
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10899
0
    return window->ScrollMax.x;
10900
0
}
10901
10902
float ImGui::GetScrollMaxY()
10903
0
{
10904
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10905
0
    return window->ScrollMax.y;
10906
0
}
10907
10908
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10909
9.12k
{
10910
9.12k
    window->ScrollTarget.x = scroll_x;
10911
9.12k
    window->ScrollTargetCenterRatio.x = 0.0f;
10912
9.12k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10913
9.12k
}
10914
10915
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10916
10.0k
{
10917
10.0k
    window->ScrollTarget.y = scroll_y;
10918
10.0k
    window->ScrollTargetCenterRatio.y = 0.0f;
10919
10.0k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10920
10.0k
}
10921
10922
void ImGui::SetScrollX(float scroll_x)
10923
8.95k
{
10924
8.95k
    ImGuiContext& g = *GImGui;
10925
8.95k
    SetScrollX(g.CurrentWindow, scroll_x);
10926
8.95k
}
10927
10928
void ImGui::SetScrollY(float scroll_y)
10929
7.44k
{
10930
7.44k
    ImGuiContext& g = *GImGui;
10931
7.44k
    SetScrollY(g.CurrentWindow, scroll_y);
10932
7.44k
}
10933
10934
// Note that a local position will vary depending on initial scroll value,
10935
// This is a little bit confusing so bear with us:
10936
//  - local_pos = (absolution_pos - window->Pos)
10937
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10938
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10939
//  - They mostly exist because of legacy API.
10940
// Following the rules above, when trying to work with scrolling code, consider that:
10941
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10942
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10943
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10944
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10945
0
{
10946
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10947
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10948
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10949
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10950
0
}
10951
10952
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10953
0
{
10954
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10955
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10956
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10957
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10958
0
}
10959
10960
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10961
0
{
10962
0
    ImGuiContext& g = *GImGui;
10963
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10964
0
}
10965
10966
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10967
0
{
10968
0
    ImGuiContext& g = *GImGui;
10969
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10970
0
}
10971
10972
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10973
void ImGui::SetScrollHereX(float center_x_ratio)
10974
0
{
10975
0
    ImGuiContext& g = *GImGui;
10976
0
    ImGuiWindow* window = g.CurrentWindow;
10977
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10978
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10979
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10980
10981
    // Tweak: snap on edges when aiming at an item very close to the edge
10982
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10983
0
}
10984
10985
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10986
void ImGui::SetScrollHereY(float center_y_ratio)
10987
0
{
10988
0
    ImGuiContext& g = *GImGui;
10989
0
    ImGuiWindow* window = g.CurrentWindow;
10990
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10991
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10992
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10993
10994
    // Tweak: snap on edges when aiming at an item very close to the edge
10995
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10996
0
}
10997
10998
//-----------------------------------------------------------------------------
10999
// [SECTION] TOOLTIPS
11000
//-----------------------------------------------------------------------------
11001
11002
bool ImGui::BeginTooltip()
11003
0
{
11004
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11005
0
}
11006
11007
bool ImGui::BeginItemTooltip()
11008
0
{
11009
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11010
0
        return false;
11011
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11012
0
}
11013
11014
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11015
0
{
11016
0
    ImGuiContext& g = *GImGui;
11017
11018
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11019
0
    {
11020
        // Drag and Drop tooltips are positioning differently than other tooltips:
11021
        // - offset visibility to increase visibility around mouse.
11022
        // - never clamp within outer viewport boundary.
11023
        // We call SetNextWindowPos() to enforce position and disable clamping.
11024
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11025
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11026
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11027
0
        SetNextWindowPos(tooltip_pos);
11028
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11029
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11030
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11031
0
    }
11032
11033
0
    char window_name[16];
11034
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11035
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11036
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11037
0
            if (window->Active)
11038
0
            {
11039
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11040
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(window);
11041
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11042
0
            }
11043
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11044
0
    Begin(window_name, NULL, flags | extra_window_flags);
11045
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11046
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11047
    //if (!ret)
11048
    //    End();
11049
    //return ret;
11050
0
    return true;
11051
0
}
11052
11053
void ImGui::EndTooltip()
11054
0
{
11055
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11056
0
    End();
11057
0
}
11058
11059
void ImGui::SetTooltip(const char* fmt, ...)
11060
0
{
11061
0
    va_list args;
11062
0
    va_start(args, fmt);
11063
0
    SetTooltipV(fmt, args);
11064
0
    va_end(args);
11065
0
}
11066
11067
void ImGui::SetTooltipV(const char* fmt, va_list args)
11068
0
{
11069
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11070
0
        return;
11071
0
    TextV(fmt, args);
11072
0
    EndTooltip();
11073
0
}
11074
11075
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11076
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11077
void ImGui::SetItemTooltip(const char* fmt, ...)
11078
0
{
11079
0
    va_list args;
11080
0
    va_start(args, fmt);
11081
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11082
0
        SetTooltipV(fmt, args);
11083
0
    va_end(args);
11084
0
}
11085
11086
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11087
0
{
11088
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11089
0
        SetTooltipV(fmt, args);
11090
0
}
11091
11092
11093
//-----------------------------------------------------------------------------
11094
// [SECTION] POPUPS
11095
//-----------------------------------------------------------------------------
11096
11097
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11098
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11099
0
{
11100
0
    ImGuiContext& g = *GImGui;
11101
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11102
0
    {
11103
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11104
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11105
0
        IM_ASSERT(id == 0);
11106
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11107
0
            return g.OpenPopupStack.Size > 0;
11108
0
        else
11109
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11110
0
    }
11111
0
    else
11112
0
    {
11113
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11114
0
        {
11115
            // Return true if the popup is open anywhere in the popup stack
11116
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11117
0
                if (popup_data.PopupId == id)
11118
0
                    return true;
11119
0
            return false;
11120
0
        }
11121
0
        else
11122
0
        {
11123
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11124
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11125
0
        }
11126
0
    }
11127
0
}
11128
11129
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11130
0
{
11131
0
    ImGuiContext& g = *GImGui;
11132
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11133
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11134
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11135
0
    return IsPopupOpen(id, popup_flags);
11136
0
}
11137
11138
// Also see FindBlockingModal(NULL)
11139
ImGuiWindow* ImGui::GetTopMostPopupModal()
11140
77.3k
{
11141
77.3k
    ImGuiContext& g = *GImGui;
11142
77.3k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11143
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11144
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11145
0
                return popup;
11146
77.3k
    return NULL;
11147
77.3k
}
11148
11149
// See Demo->Stacked Modal to confirm what this is for.
11150
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11151
25.7k
{
11152
25.7k
    ImGuiContext& g = *GImGui;
11153
25.7k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11154
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11155
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11156
0
                return popup;
11157
25.7k
    return NULL;
11158
25.7k
}
11159
11160
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11161
0
{
11162
0
    ImGuiContext& g = *GImGui;
11163
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11164
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11165
0
    OpenPopupEx(id, popup_flags);
11166
0
}
11167
11168
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11169
0
{
11170
0
    OpenPopupEx(id, popup_flags);
11171
0
}
11172
11173
// Mark popup as open (toggle toward open state).
11174
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11175
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11176
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11177
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11178
0
{
11179
0
    ImGuiContext& g = *GImGui;
11180
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11181
0
    const int current_stack_size = g.BeginPopupStack.Size;
11182
11183
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11184
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11185
0
            return;
11186
11187
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11188
0
    popup_ref.PopupId = id;
11189
0
    popup_ref.Window = NULL;
11190
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
11191
0
    popup_ref.OpenFrameCount = g.FrameCount;
11192
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11193
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11194
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11195
11196
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11197
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11198
0
    {
11199
0
        g.OpenPopupStack.push_back(popup_ref);
11200
0
    }
11201
0
    else
11202
0
    {
11203
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
11204
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
11205
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
11206
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
11207
0
        {
11208
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11209
0
        }
11210
0
        else
11211
0
        {
11212
            // Close child popups if any, then flag popup for open/reopen
11213
0
            ClosePopupToLevel(current_stack_size, false);
11214
0
            g.OpenPopupStack.push_back(popup_ref);
11215
0
        }
11216
11217
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11218
        // This is equivalent to what ClosePopupToLevel() does.
11219
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11220
        //    FocusWindow(parent_window);
11221
0
    }
11222
0
}
11223
11224
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11225
// This function closes any popups that are over 'ref_window'.
11226
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11227
2.67k
{
11228
2.67k
    ImGuiContext& g = *GImGui;
11229
2.67k
    if (g.OpenPopupStack.Size == 0)
11230
2.67k
        return;
11231
11232
    // Don't close our own child popup windows.
11233
0
    int popup_count_to_keep = 0;
11234
0
    if (ref_window)
11235
0
    {
11236
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11237
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11238
0
        {
11239
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11240
0
            if (!popup.Window)
11241
0
                continue;
11242
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11243
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
11244
0
                continue;
11245
11246
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11247
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
11248
            //     Window -> Popup1 -> Popup2 -> Popup3
11249
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11250
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11251
0
            bool ref_window_is_descendent_of_popup = false;
11252
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11253
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11254
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11255
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11256
0
                    {
11257
0
                        ref_window_is_descendent_of_popup = true;
11258
0
                        break;
11259
0
                    }
11260
0
            if (!ref_window_is_descendent_of_popup)
11261
0
                break;
11262
0
        }
11263
0
    }
11264
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11265
0
    {
11266
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11267
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11268
0
    }
11269
0
}
11270
11271
void ImGui::ClosePopupsExceptModals()
11272
0
{
11273
0
    ImGuiContext& g = *GImGui;
11274
11275
0
    int popup_count_to_keep;
11276
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11277
0
    {
11278
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11279
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11280
0
            break;
11281
0
    }
11282
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11283
0
        ClosePopupToLevel(popup_count_to_keep, true);
11284
0
}
11285
11286
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11287
0
{
11288
0
    ImGuiContext& g = *GImGui;
11289
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
11290
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11291
11292
    // Trim open popup stack
11293
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
11294
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
11295
0
    g.OpenPopupStack.resize(remaining);
11296
11297
0
    if (restore_focus_to_window_under_popup)
11298
0
    {
11299
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
11300
0
        if (focus_window && !focus_window->WasActive && popup_window)
11301
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11302
0
        else
11303
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11304
0
    }
11305
0
}
11306
11307
// Close the popup we have begin-ed into.
11308
void ImGui::CloseCurrentPopup()
11309
0
{
11310
0
    ImGuiContext& g = *GImGui;
11311
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11312
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11313
0
        return;
11314
11315
    // Closing a menu closes its top-most parent popup (unless a modal)
11316
0
    while (popup_idx > 0)
11317
0
    {
11318
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11319
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11320
0
        bool close_parent = false;
11321
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11322
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11323
0
                close_parent = true;
11324
0
        if (!close_parent)
11325
0
            break;
11326
0
        popup_idx--;
11327
0
    }
11328
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11329
0
    ClosePopupToLevel(popup_idx, true);
11330
11331
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11332
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11333
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11334
0
    if (ImGuiWindow* window = g.NavWindow)
11335
0
        window->DC.NavHideHighlightOneFrame = true;
11336
0
}
11337
11338
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11339
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11340
0
{
11341
0
    ImGuiContext& g = *GImGui;
11342
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11343
0
    {
11344
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11345
0
        return false;
11346
0
    }
11347
11348
0
    char name[20];
11349
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11350
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
11351
0
    else
11352
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11353
11354
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11355
0
    bool is_open = Begin(name, NULL, flags);
11356
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11357
0
        EndPopup();
11358
11359
0
    return is_open;
11360
0
}
11361
11362
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11363
0
{
11364
0
    ImGuiContext& g = *GImGui;
11365
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11366
0
    {
11367
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11368
0
        return false;
11369
0
    }
11370
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11371
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11372
0
    return BeginPopupEx(id, flags);
11373
0
}
11374
11375
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11376
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
11377
// - *p_open set back to false in BeginPopupModal() when popup is not open.
11378
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
11379
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11380
0
{
11381
0
    ImGuiContext& g = *GImGui;
11382
0
    ImGuiWindow* window = g.CurrentWindow;
11383
0
    const ImGuiID id = window->GetID(name);
11384
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11385
0
    {
11386
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11387
0
        if (p_open && *p_open)
11388
0
            *p_open = false;
11389
0
        return false;
11390
0
    }
11391
11392
    // Center modal windows by default for increased visibility
11393
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11394
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11395
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11396
0
    {
11397
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11398
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11399
0
    }
11400
11401
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11402
0
    const bool is_open = Begin(name, p_open, flags);
11403
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11404
0
    {
11405
0
        EndPopup();
11406
0
        if (is_open)
11407
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11408
0
        return false;
11409
0
    }
11410
0
    return is_open;
11411
0
}
11412
11413
void ImGui::EndPopup()
11414
0
{
11415
0
    ImGuiContext& g = *GImGui;
11416
0
    ImGuiWindow* window = g.CurrentWindow;
11417
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11418
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11419
11420
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11421
0
    if (g.NavWindow == window)
11422
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11423
11424
    // Child-popups don't need to be laid out
11425
0
    IM_ASSERT(g.WithinEndChild == false);
11426
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11427
0
        g.WithinEndChild = true;
11428
0
    End();
11429
0
    g.WithinEndChild = false;
11430
0
}
11431
11432
// Helper to open a popup if mouse button is released over the item
11433
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11434
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11435
0
{
11436
0
    ImGuiContext& g = *GImGui;
11437
0
    ImGuiWindow* window = g.CurrentWindow;
11438
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11439
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11440
0
    {
11441
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11442
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11443
0
        OpenPopupEx(id, popup_flags);
11444
0
    }
11445
0
}
11446
11447
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11448
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11449
// - To create a popup with a specific identifier, pass it in str_id.
11450
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11451
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11452
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11453
//   This is essentially the same as:
11454
//       id = str_id ? GetID(str_id) : GetItemID();
11455
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11456
//       return BeginPopup(id);
11457
//   Which is essentially the same as:
11458
//       id = str_id ? GetID(str_id) : GetItemID();
11459
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11460
//           OpenPopup(id);
11461
//       return BeginPopup(id);
11462
//   The main difference being that this is tweaked to avoid computing the ID twice.
11463
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11464
0
{
11465
0
    ImGuiContext& g = *GImGui;
11466
0
    ImGuiWindow* window = g.CurrentWindow;
11467
0
    if (window->SkipItems)
11468
0
        return false;
11469
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11470
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11471
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11472
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11473
0
        OpenPopupEx(id, popup_flags);
11474
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11475
0
}
11476
11477
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11478
0
{
11479
0
    ImGuiContext& g = *GImGui;
11480
0
    ImGuiWindow* window = g.CurrentWindow;
11481
0
    if (!str_id)
11482
0
        str_id = "window_context";
11483
0
    ImGuiID id = window->GetID(str_id);
11484
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11485
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11486
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11487
0
            OpenPopupEx(id, popup_flags);
11488
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11489
0
}
11490
11491
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11492
0
{
11493
0
    ImGuiContext& g = *GImGui;
11494
0
    ImGuiWindow* window = g.CurrentWindow;
11495
0
    if (!str_id)
11496
0
        str_id = "void_context";
11497
0
    ImGuiID id = window->GetID(str_id);
11498
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11499
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11500
0
        if (GetTopMostPopupModal() == NULL)
11501
0
            OpenPopupEx(id, popup_flags);
11502
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11503
0
}
11504
11505
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11506
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11507
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11508
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11509
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11510
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11511
0
{
11512
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11513
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11514
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11515
11516
    // Combo Box policy (we want a connecting edge)
11517
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11518
0
    {
11519
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11520
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11521
0
        {
11522
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11523
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11524
0
                continue;
11525
0
            ImVec2 pos;
11526
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11527
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11528
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11529
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11530
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11531
0
                continue;
11532
0
            *last_dir = dir;
11533
0
            return pos;
11534
0
        }
11535
0
    }
11536
11537
    // Tooltip and Default popup policy
11538
    // (Always first try the direction we used on the last frame, if any)
11539
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11540
0
    {
11541
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11542
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11543
0
        {
11544
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11545
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11546
0
                continue;
11547
11548
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11549
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11550
11551
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11552
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11553
0
                continue;
11554
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11555
0
                continue;
11556
11557
0
            ImVec2 pos;
11558
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11559
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11560
11561
            // Clamp top-left corner of popup
11562
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11563
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11564
11565
0
            *last_dir = dir;
11566
0
            return pos;
11567
0
        }
11568
0
    }
11569
11570
    // Fallback when not enough room:
11571
0
    *last_dir = ImGuiDir_None;
11572
11573
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11574
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11575
0
        return ref_pos + ImVec2(2, 2);
11576
11577
    // Otherwise try to keep within display
11578
0
    ImVec2 pos = ref_pos;
11579
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11580
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11581
0
    return pos;
11582
0
}
11583
11584
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11585
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11586
0
{
11587
0
    ImGuiContext& g = *GImGui;
11588
0
    ImRect r_screen;
11589
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11590
0
    {
11591
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11592
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11593
0
        r_screen.Min = monitor.WorkPos;
11594
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11595
0
    }
11596
0
    else
11597
0
    {
11598
        // Use the full viewport area (not work area) for popups
11599
0
        r_screen = window->Viewport->GetMainRect();
11600
0
    }
11601
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11602
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11603
0
    return r_screen;
11604
0
}
11605
11606
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11607
0
{
11608
0
    ImGuiContext& g = *GImGui;
11609
11610
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11611
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11612
0
    {
11613
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11614
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11615
0
        ImGuiWindow* parent_window = window->ParentWindow;
11616
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11617
0
        ImRect r_avoid;
11618
0
        if (parent_window->DC.MenuBarAppending)
11619
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11620
0
        else
11621
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11622
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11623
0
    }
11624
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11625
0
    {
11626
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11627
0
    }
11628
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11629
0
    {
11630
        // Position tooltip (always follows mouse + clamp within outer boundaries)
11631
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11632
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11633
0
        IM_ASSERT(g.CurrentWindow == window);
11634
0
        const float scale = g.Style.MouseCursorScale;
11635
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
11636
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11637
0
        ImRect r_avoid;
11638
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11639
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11640
0
        else
11641
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11642
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11643
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11644
0
    }
11645
0
    IM_ASSERT(0);
11646
0
    return window->Pos;
11647
0
}
11648
11649
//-----------------------------------------------------------------------------
11650
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11651
//-----------------------------------------------------------------------------
11652
11653
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11654
// In our terminology those should be interchangeable, yet right now this is super confusing.
11655
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11656
11657
void ImGui::SetNavWindow(ImGuiWindow* window)
11658
2.68k
{
11659
2.68k
    ImGuiContext& g = *GImGui;
11660
2.68k
    if (g.NavWindow != window)
11661
2.68k
    {
11662
2.68k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11663
2.68k
        g.NavWindow = window;
11664
2.68k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
11665
2.68k
    }
11666
2.68k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11667
2.68k
    NavUpdateAnyRequestFlag();
11668
2.68k
}
11669
11670
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11671
2.72k
{
11672
2.72k
    ImGuiContext& g = *GImGui;
11673
2.72k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11674
2.72k
}
11675
11676
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11677
230
{
11678
230
    ImGuiContext& g = *GImGui;
11679
230
    IM_ASSERT(g.NavWindow != NULL);
11680
230
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11681
230
    g.NavId = id;
11682
230
    g.NavLayer = nav_layer;
11683
230
    g.NavFocusScopeId = focus_scope_id;
11684
230
    g.NavWindow->NavLastIds[nav_layer] = id;
11685
230
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11686
11687
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11688
230
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11689
230
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11690
230
}
11691
11692
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11693
12
{
11694
12
    ImGuiContext& g = *GImGui;
11695
12
    IM_ASSERT(id != 0);
11696
11697
12
    if (g.NavWindow != window)
11698
12
       SetNavWindow(window);
11699
11700
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11701
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11702
12
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11703
12
    g.NavId = id;
11704
12
    g.NavLayer = nav_layer;
11705
12
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11706
12
    window->NavLastIds[nav_layer] = id;
11707
12
    if (g.LastItemData.ID == id)
11708
12
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11709
11710
12
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11711
0
        g.NavDisableMouseHover = true;
11712
12
    else
11713
12
        g.NavDisableHighlight = true;
11714
11715
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11716
12
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11717
12
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11718
12
}
11719
11720
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11721
22
{
11722
22
    if (ImFabs(dx) > ImFabs(dy))
11723
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11724
22
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11725
22
}
11726
11727
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11728
44
{
11729
44
    if (cand_max < curr_min)
11730
0
        return cand_max - curr_min;
11731
44
    if (curr_max < cand_min)
11732
22
        return cand_min - curr_max;
11733
22
    return 0.0f;
11734
44
}
11735
11736
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11737
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11738
60
{
11739
60
    ImGuiContext& g = *GImGui;
11740
60
    ImGuiWindow* window = g.CurrentWindow;
11741
60
    if (g.NavLayer != window->DC.NavLayerCurrent)
11742
38
        return false;
11743
11744
    // FIXME: Those are not good variables names
11745
22
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11746
22
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11747
22
    g.NavScoringDebugCount++;
11748
11749
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11750
22
    if (window->ParentWindow == g.NavWindow)
11751
0
    {
11752
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11753
0
        if (!window->ClipRect.Overlaps(cand))
11754
0
            return false;
11755
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11756
0
    }
11757
11758
    // Compute distance between boxes
11759
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11760
22
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11761
22
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11762
22
    if (dby != 0.0f && dbx != 0.0f)
11763
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11764
22
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11765
11766
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11767
22
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11768
22
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11769
22
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11770
11771
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11772
22
    ImGuiDir quadrant;
11773
22
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11774
22
    if (dbx != 0.0f || dby != 0.0f)
11775
22
    {
11776
        // For non-overlapping boxes, use distance between boxes
11777
22
        dax = dbx;
11778
22
        day = dby;
11779
22
        dist_axial = dist_box;
11780
22
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11781
22
    }
11782
0
    else if (dcx != 0.0f || dcy != 0.0f)
11783
0
    {
11784
        // For overlapping boxes with different centers, use distance between centers
11785
0
        dax = dcx;
11786
0
        day = dcy;
11787
0
        dist_axial = dist_center;
11788
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11789
0
    }
11790
0
    else
11791
0
    {
11792
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11793
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11794
0
    }
11795
11796
22
    const ImGuiDir move_dir = g.NavMoveDir;
11797
#if IMGUI_DEBUG_NAV_SCORING
11798
    char buf[200];
11799
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11800
    {
11801
        if (quadrant == move_dir)
11802
        {
11803
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11804
            ImDrawList* draw_list = GetForegroundDrawList(window);
11805
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11806
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11807
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11808
        }
11809
    }
11810
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11811
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11812
    if (debug_hovering || debug_tty)
11813
    {
11814
        ImFormatString(buf, IM_ARRAYSIZE(buf),
11815
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
11816
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11817
        if (debug_hovering)
11818
        {
11819
            ImDrawList* draw_list = GetForegroundDrawList(window);
11820
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11821
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11822
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11823
            draw_list->AddText(cand.Max, ~0U, buf);
11824
        }
11825
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11826
    }
11827
#endif
11828
11829
    // Is it in the quadrant we're interested in moving to?
11830
22
    bool new_best = false;
11831
22
    if (quadrant == move_dir)
11832
22
    {
11833
        // Does it beat the current best candidate?
11834
22
        if (dist_box < result->DistBox)
11835
22
        {
11836
22
            result->DistBox = dist_box;
11837
22
            result->DistCenter = dist_center;
11838
22
            return true;
11839
22
        }
11840
0
        if (dist_box == result->DistBox)
11841
0
        {
11842
            // Try using distance between center points to break ties
11843
0
            if (dist_center < result->DistCenter)
11844
0
            {
11845
0
                result->DistCenter = dist_center;
11846
0
                new_best = true;
11847
0
            }
11848
0
            else if (dist_center == result->DistCenter)
11849
0
            {
11850
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11851
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11852
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11853
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11854
0
                    new_best = true;
11855
0
            }
11856
0
        }
11857
0
    }
11858
11859
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11860
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11861
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11862
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11863
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11864
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11865
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11866
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11867
0
            {
11868
0
                result->DistAxial = dist_axial;
11869
0
                new_best = true;
11870
0
            }
11871
11872
0
    return new_best;
11873
22
}
11874
11875
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11876
188
{
11877
188
    ImGuiContext& g = *GImGui;
11878
188
    ImGuiWindow* window = g.CurrentWindow;
11879
188
    result->Window = window;
11880
188
    result->ID = g.LastItemData.ID;
11881
188
    result->FocusScopeId = g.CurrentFocusScopeId;
11882
188
    result->InFlags = g.LastItemData.InFlags;
11883
188
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11884
188
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
11885
0
    {
11886
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11887
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11888
0
    }
11889
188
}
11890
11891
// True when current work location may be scrolled horizontally when moving left / right.
11892
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11893
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11894
128k
{
11895
128k
    ImGuiContext& g = *GImGui;
11896
128k
    ImGuiWindow* window = g.CurrentWindow;
11897
128k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11898
128k
}
11899
11900
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11901
// This is called after LastItemData is set, but NextItemData is also still valid.
11902
static void ImGui::NavProcessItem()
11903
1.07k
{
11904
1.07k
    ImGuiContext& g = *GImGui;
11905
1.07k
    ImGuiWindow* window = g.CurrentWindow;
11906
1.07k
    const ImGuiID id = g.LastItemData.ID;
11907
1.07k
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11908
11909
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11910
1.07k
    if (window->DC.NavIsScrollPushableX == false)
11911
0
    {
11912
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11913
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11914
0
    }
11915
1.07k
    const ImRect nav_bb = g.LastItemData.NavRect;
11916
11917
    // Process Init Request
11918
1.07k
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11919
0
    {
11920
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11921
0
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11922
0
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
11923
0
        {
11924
0
            NavApplyItemToResult(&g.NavInitResult);
11925
0
        }
11926
0
        if (candidate_for_nav_default_focus)
11927
0
        {
11928
0
            g.NavInitRequest = false; // Found a match, clear request
11929
0
            NavUpdateAnyRequestFlag();
11930
0
        }
11931
0
    }
11932
11933
    // Process Move Request (scoring for navigation)
11934
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11935
1.07k
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11936
386
    {
11937
386
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
11938
386
        if (is_tabbing)
11939
332
        {
11940
332
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11941
332
        }
11942
54
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11943
38
        {
11944
38
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11945
38
            if (NavScoreItem(result))
11946
11
                NavApplyItemToResult(result);
11947
11948
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11949
38
            const float VISIBLE_RATIO = 0.70f;
11950
38
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11951
22
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11952
22
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11953
11
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11954
38
        }
11955
386
    }
11956
11957
    // Update information for currently focused/navigated item
11958
1.07k
    if (g.NavId == id)
11959
875
    {
11960
875
        if (g.NavWindow != window)
11961
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11962
875
        g.NavLayer = window->DC.NavLayerCurrent;
11963
875
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11964
875
        g.NavIdIsAlive = true;
11965
875
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
11966
0
        {
11967
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
11968
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
11969
0
        }
11970
875
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
11971
875
    }
11972
1.07k
}
11973
11974
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11975
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11976
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11977
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11978
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11979
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11980
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11981
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11982
332
{
11983
332
    ImGuiContext& g = *GImGui;
11984
11985
332
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11986
332
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11987
166
            return;
11988
11989
    // - Can always land on an item when using API call.
11990
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11991
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11992
166
    bool can_stop;
11993
166
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11994
0
        can_stop = true;
11995
166
    else
11996
166
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11997
11998
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11999
166
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12000
166
    if (g.NavTabbingDir == +1)
12001
166
    {
12002
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12003
166
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12004
166
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12005
166
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12006
0
            NavMoveRequestResolveWithLastItem(result);
12007
166
        else if (g.NavId == id)
12008
166
            g.NavTabbingCounter = 1;
12009
166
    }
12010
0
    else if (g.NavTabbingDir == -1)
12011
0
    {
12012
        // Tab Backward
12013
0
        if (g.NavId == id)
12014
0
        {
12015
0
            if (result->ID)
12016
0
            {
12017
0
                g.NavMoveScoringItems = false;
12018
0
                NavUpdateAnyRequestFlag();
12019
0
            }
12020
0
        }
12021
0
        else if (can_stop)
12022
0
        {
12023
            // Keep applying until reaching NavId
12024
0
            NavApplyItemToResult(result);
12025
0
        }
12026
0
    }
12027
0
    else if (g.NavTabbingDir == 0)
12028
0
    {
12029
0
        if (can_stop && g.NavId == id)
12030
0
            NavMoveRequestResolveWithLastItem(result);
12031
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12032
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12033
0
    }
12034
166
}
12035
12036
bool ImGui::NavMoveRequestButNoResultYet()
12037
24.4k
{
12038
24.4k
    ImGuiContext& g = *GImGui;
12039
24.4k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12040
24.4k
}
12041
12042
// FIXME: ScoringRect is not set
12043
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12044
2.46k
{
12045
2.46k
    ImGuiContext& g = *GImGui;
12046
2.46k
    IM_ASSERT(g.NavWindow != NULL);
12047
12048
2.46k
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12049
2.03k
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12050
12051
2.46k
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12052
2.46k
    g.NavMoveDir = move_dir;
12053
2.46k
    g.NavMoveDirForDebug = move_dir;
12054
2.46k
    g.NavMoveClipDir = clip_dir;
12055
2.46k
    g.NavMoveFlags = move_flags;
12056
2.46k
    g.NavMoveScrollFlags = scroll_flags;
12057
2.46k
    g.NavMoveForwardToNextFrame = false;
12058
2.46k
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12059
2.46k
    g.NavMoveResultLocal.Clear();
12060
2.46k
    g.NavMoveResultLocalVisible.Clear();
12061
2.46k
    g.NavMoveResultOther.Clear();
12062
2.46k
    g.NavTabbingCounter = 0;
12063
2.46k
    g.NavTabbingResultFirst.Clear();
12064
2.46k
    NavUpdateAnyRequestFlag();
12065
2.46k
}
12066
12067
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12068
0
{
12069
0
    ImGuiContext& g = *GImGui;
12070
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12071
0
    NavApplyItemToResult(result);
12072
0
    NavUpdateAnyRequestFlag();
12073
0
}
12074
12075
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12076
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiNavTreeNodeData* tree_node_data)
12077
0
{
12078
0
    ImGuiContext& g = *GImGui;
12079
0
    g.NavMoveScoringItems = false;
12080
0
    g.LastItemData.ID = tree_node_data->ID;
12081
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12082
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12083
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12084
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12085
0
    NavUpdateAnyRequestFlag();
12086
0
}
12087
12088
void ImGui::NavMoveRequestCancel()
12089
0
{
12090
0
    ImGuiContext& g = *GImGui;
12091
0
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12092
0
    NavUpdateAnyRequestFlag();
12093
0
}
12094
12095
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12096
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12097
0
{
12098
0
    ImGuiContext& g = *GImGui;
12099
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12100
0
    NavMoveRequestCancel();
12101
0
    g.NavMoveForwardToNextFrame = true;
12102
0
    g.NavMoveDir = move_dir;
12103
0
    g.NavMoveClipDir = clip_dir;
12104
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12105
0
    g.NavMoveScrollFlags = scroll_flags;
12106
0
}
12107
12108
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12109
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12110
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12111
0
{
12112
0
    ImGuiContext& g = *GImGui;
12113
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12114
12115
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12116
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12117
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12118
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12119
0
}
12120
12121
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12122
// This way we could find the last focused window among our children. It would be much less confusing this way?
12123
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12124
23.1k
{
12125
23.1k
    ImGuiWindow* parent = nav_window;
12126
45.4k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12127
22.2k
        parent = parent->ParentWindow;
12128
23.1k
    if (parent && parent != nav_window)
12129
22.2k
        parent->NavLastChildNavWindow = nav_window;
12130
23.1k
}
12131
12132
// Restore the last focused child.
12133
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12134
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12135
0
{
12136
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12137
0
        return window->NavLastChildNavWindow;
12138
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12139
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12140
0
            return tab->Window;
12141
0
    return window;
12142
0
}
12143
12144
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12145
0
{
12146
0
    ImGuiContext& g = *GImGui;
12147
0
    if (layer == ImGuiNavLayer_Main)
12148
0
    {
12149
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
12150
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12151
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12152
0
        if (prev_nav_window)
12153
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12154
0
    }
12155
0
    ImGuiWindow* window = g.NavWindow;
12156
0
    if (window->NavLastIds[layer] != 0)
12157
0
    {
12158
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12159
0
    }
12160
0
    else
12161
0
    {
12162
0
        g.NavLayer = layer;
12163
0
        NavInitWindow(window, true);
12164
0
    }
12165
0
}
12166
12167
void ImGui::NavRestoreHighlightAfterMove()
12168
240
{
12169
240
    ImGuiContext& g = *GImGui;
12170
240
    g.NavDisableHighlight = false;
12171
240
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12172
240
}
12173
12174
static inline void ImGui::NavUpdateAnyRequestFlag()
12175
30.9k
{
12176
30.9k
    ImGuiContext& g = *GImGui;
12177
30.9k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12178
30.9k
    if (g.NavAnyRequest)
12179
30.9k
        IM_ASSERT(g.NavWindow != NULL);
12180
30.9k
}
12181
12182
// This needs to be called before we submit any widget (aka in or before Begin)
12183
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12184
2
{
12185
    // FIXME: ChildWindow test here is wrong for docking
12186
2
    ImGuiContext& g = *GImGui;
12187
2
    IM_ASSERT(window == g.NavWindow);
12188
12189
2
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12190
0
    {
12191
0
        g.NavId = 0;
12192
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12193
0
        return;
12194
0
    }
12195
12196
2
    bool init_for_nav = false;
12197
2
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12198
2
        init_for_nav = true;
12199
2
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12200
2
    if (init_for_nav)
12201
2
    {
12202
2
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12203
2
        g.NavInitRequest = true;
12204
2
        g.NavInitRequestFromMove = false;
12205
2
        g.NavInitResult.ID = 0;
12206
2
        NavUpdateAnyRequestFlag();
12207
2
    }
12208
0
    else
12209
0
    {
12210
0
        g.NavId = window->NavLastIds[0];
12211
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
12212
0
    }
12213
2
}
12214
12215
static ImVec2 ImGui::NavCalcPreferredRefPos()
12216
0
{
12217
0
    ImGuiContext& g = *GImGui;
12218
0
    ImGuiWindow* window = g.NavWindow;
12219
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
12220
0
    {
12221
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12222
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12223
        // In theory we could move that +1.0f offset in OpenPopupEx()
12224
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12225
0
        return ImVec2(p.x + 1.0f, p.y);
12226
0
    }
12227
0
    else
12228
0
    {
12229
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12230
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12231
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12232
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12233
0
        {
12234
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12235
0
            rect_rel.Translate(window->Scroll - next_scroll);
12236
0
        }
12237
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12238
0
        ImGuiViewport* viewport = window->Viewport;
12239
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12240
0
    }
12241
0
}
12242
12243
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12244
0
{
12245
0
    ImGuiContext& g = *GImGui;
12246
0
    float repeat_delay, repeat_rate;
12247
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12248
12249
0
    ImGuiKey key_less, key_more;
12250
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12251
0
    {
12252
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12253
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12254
0
    }
12255
0
    else
12256
0
    {
12257
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12258
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12259
0
    }
12260
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12261
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12262
0
        amount = 0.0f;
12263
0
    return amount;
12264
0
}
12265
12266
static void ImGui::NavUpdate()
12267
25.7k
{
12268
25.7k
    ImGuiContext& g = *GImGui;
12269
25.7k
    ImGuiIO& io = g.IO;
12270
12271
25.7k
    io.WantSetMousePos = false;
12272
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12273
12274
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12275
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12276
25.7k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12277
25.7k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12278
25.7k
    if (nav_gamepad_active)
12279
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12280
0
            if (IsKeyDown(key))
12281
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12282
25.7k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12283
25.7k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12284
25.7k
    if (nav_keyboard_active)
12285
25.7k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12286
180k
            if (IsKeyDown(key))
12287
3.09k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12288
12289
    // Process navigation init request (select first/default focus)
12290
25.7k
    g.NavJustMovedToId = 0;
12291
25.7k
    if (g.NavInitResult.ID != 0)
12292
0
        NavInitRequestApplyResult();
12293
25.7k
    g.NavInitRequest = false;
12294
25.7k
    g.NavInitRequestFromMove = false;
12295
25.7k
    g.NavInitResult.ID = 0;
12296
12297
    // Process navigation move request
12298
25.7k
    if (g.NavMoveSubmitted)
12299
2.41k
        NavMoveRequestApplyResult();
12300
25.7k
    g.NavTabbingCounter = 0;
12301
25.7k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12302
12303
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12304
25.7k
    bool set_mouse_pos = false;
12305
25.7k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12306
233
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12307
233
            set_mouse_pos = true;
12308
25.7k
    g.NavMousePosDirty = false;
12309
25.7k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12310
12311
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12312
25.7k
    if (g.NavWindow)
12313
23.1k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12314
25.7k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12315
50
        g.NavWindow->NavLastChildNavWindow = NULL;
12316
12317
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12318
25.7k
    NavUpdateWindowing();
12319
12320
    // Set output flags for user application
12321
25.7k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12322
25.7k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12323
12324
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12325
25.7k
    NavUpdateCancelRequest();
12326
12327
    // Process manual activation request
12328
25.7k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12329
25.7k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12330
25.7k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12331
881
    {
12332
881
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
12333
881
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
12334
881
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
12335
881
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
12336
881
        if (g.ActiveId == 0 && activate_pressed)
12337
0
        {
12338
0
            g.NavActivateId = g.NavId;
12339
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12340
0
        }
12341
881
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12342
0
        {
12343
0
            g.NavActivateId = g.NavId;
12344
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12345
0
        }
12346
881
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12347
10
            g.NavActivateDownId = g.NavId;
12348
881
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12349
0
            g.NavActivatePressedId = g.NavId;
12350
881
    }
12351
25.7k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12352
0
        g.NavDisableHighlight = true;
12353
25.7k
    if (g.NavActivateId != 0)
12354
25.7k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12355
12356
    // Process programmatic activation request
12357
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12358
25.7k
    if (g.NavNextActivateId != 0)
12359
0
    {
12360
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12361
0
        g.NavActivateFlags = g.NavNextActivateFlags;
12362
0
    }
12363
25.7k
    g.NavNextActivateId = 0;
12364
12365
    // Process move requests
12366
25.7k
    NavUpdateCreateMoveRequest();
12367
25.7k
    if (g.NavMoveDir == ImGuiDir_None)
12368
25.3k
        NavUpdateCreateTabbingRequest();
12369
25.7k
    NavUpdateAnyRequestFlag();
12370
25.7k
    g.NavIdIsAlive = false;
12371
12372
    // Scrolling
12373
25.7k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12374
23.1k
    {
12375
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12376
23.1k
        ImGuiWindow* window = g.NavWindow;
12377
23.1k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12378
23.1k
        const ImGuiDir move_dir = g.NavMoveDir;
12379
23.1k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12380
404
        {
12381
404
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12382
177
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12383
404
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12384
227
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12385
404
        }
12386
12387
        // *Normal* Manual scroll with LStick
12388
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12389
23.1k
        if (nav_gamepad_active)
12390
0
        {
12391
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12392
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12393
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12394
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12395
0
            if (scroll_dir.y != 0.0f)
12396
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12397
0
        }
12398
23.1k
    }
12399
12400
    // Always prioritize mouse highlight if navigation is disabled
12401
25.7k
    if (!nav_keyboard_active && !nav_gamepad_active)
12402
0
    {
12403
0
        g.NavDisableHighlight = true;
12404
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12405
0
    }
12406
12407
    // Update mouse position if requested
12408
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12409
25.7k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12410
0
        TeleportMousePos(NavCalcPreferredRefPos());
12411
12412
    // [DEBUG]
12413
25.7k
    g.NavScoringDebugCount = 0;
12414
#if IMGUI_DEBUG_NAV_RECTS
12415
    if (ImGuiWindow* debug_window = g.NavWindow)
12416
    {
12417
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12418
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12419
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12420
    }
12421
#endif
12422
25.7k
}
12423
12424
void ImGui::NavInitRequestApplyResult()
12425
0
{
12426
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12427
0
    ImGuiContext& g = *GImGui;
12428
0
    if (!g.NavWindow)
12429
0
        return;
12430
12431
0
    ImGuiNavItemData* result = &g.NavInitResult;
12432
0
    if (g.NavId != result->ID)
12433
0
    {
12434
0
        g.NavJustMovedToId = result->ID;
12435
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12436
0
        g.NavJustMovedToKeyMods = 0;
12437
0
    }
12438
12439
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12440
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12441
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12442
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12443
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12444
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12445
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12446
0
    if (g.NavInitRequestFromMove)
12447
0
        NavRestoreHighlightAfterMove();
12448
0
}
12449
12450
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12451
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12452
431
{
12453
    // Bias initial rect
12454
431
    ImGuiContext& g = *GImGui;
12455
431
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12456
12457
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12458
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12459
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12460
431
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12461
431
    {
12462
431
        if (preferred_pos_rel.x == FLT_MAX)
12463
211
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12464
431
        if (preferred_pos_rel.y == FLT_MAX)
12465
236
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12466
431
    }
12467
12468
    // Apply general bias on the other axis
12469
431
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12470
239
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12471
192
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12472
192
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12473
431
}
12474
12475
void ImGui::NavUpdateCreateMoveRequest()
12476
25.7k
{
12477
25.7k
    ImGuiContext& g = *GImGui;
12478
25.7k
    ImGuiIO& io = g.IO;
12479
25.7k
    ImGuiWindow* window = g.NavWindow;
12480
25.7k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12481
25.7k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12482
12483
25.7k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12484
0
    {
12485
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12486
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12487
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12488
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12489
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12490
0
    }
12491
25.7k
    else
12492
25.7k
    {
12493
        // Initiate directional inputs request
12494
25.7k
        g.NavMoveDir = ImGuiDir_None;
12495
25.7k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12496
25.7k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12497
25.7k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12498
23.1k
        {
12499
23.1k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12500
23.1k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12501
23.1k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12502
23.1k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12503
23.1k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12504
23.1k
        }
12505
25.7k
        g.NavMoveClipDir = g.NavMoveDir;
12506
25.7k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12507
25.7k
    }
12508
12509
    // Update PageUp/PageDown/Home/End scroll
12510
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12511
25.7k
    float scoring_rect_offset_y = 0.0f;
12512
25.7k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12513
22.7k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12514
25.7k
    if (scoring_rect_offset_y != 0.0f)
12515
11
    {
12516
11
        g.NavScoringNoClipRect = window->InnerRect;
12517
11
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12518
11
    }
12519
12520
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12521
#if IMGUI_DEBUG_NAV_SCORING
12522
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12523
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12524
    if (io.KeyCtrl)
12525
    {
12526
        if (g.NavMoveDir == ImGuiDir_None)
12527
            g.NavMoveDir = g.NavMoveDirForDebug;
12528
        g.NavMoveClipDir = g.NavMoveDir;
12529
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12530
    }
12531
#endif
12532
12533
    // Submit
12534
25.7k
    g.NavMoveForwardToNextFrame = false;
12535
25.7k
    if (g.NavMoveDir != ImGuiDir_None)
12536
431
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12537
12538
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12539
25.7k
    if (g.NavMoveSubmitted && g.NavId == 0)
12540
404
    {
12541
404
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12542
404
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12543
404
        g.NavInitResult.ID = 0;
12544
404
        g.NavDisableHighlight = false;
12545
404
    }
12546
12547
    // When using gamepad, we project the reference nav bounding box into window visible area.
12548
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12549
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12550
25.7k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12551
0
    {
12552
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12553
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12554
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12555
12556
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12557
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12558
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12559
12560
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12561
0
        {
12562
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12563
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12564
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12565
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12566
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12567
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12568
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12569
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12570
0
            g.NavId = 0;
12571
0
        }
12572
0
    }
12573
12574
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12575
25.7k
    ImRect scoring_rect;
12576
25.7k
    if (window != NULL)
12577
23.1k
    {
12578
23.1k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12579
23.1k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12580
23.1k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12581
23.1k
        if (g.NavMoveSubmitted)
12582
431
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12583
23.1k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12584
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12585
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12586
23.1k
    }
12587
25.7k
    g.NavScoringRect = scoring_rect;
12588
25.7k
    g.NavScoringNoClipRect.Add(scoring_rect);
12589
25.7k
}
12590
12591
void ImGui::NavUpdateCreateTabbingRequest()
12592
25.3k
{
12593
25.3k
    ImGuiContext& g = *GImGui;
12594
25.3k
    ImGuiWindow* window = g.NavWindow;
12595
25.3k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12596
25.3k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12597
2.57k
        return;
12598
12599
22.7k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12600
22.7k
    if (!tab_pressed)
12601
20.7k
        return;
12602
12603
    // Initiate tabbing request
12604
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12605
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12606
2.03k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12607
2.03k
    if (nav_keyboard_active)
12608
2.03k
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12609
0
    else
12610
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12611
2.03k
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
12612
2.03k
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12613
2.03k
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12614
2.03k
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12615
2.03k
    g.NavTabbingCounter = -1;
12616
2.03k
}
12617
12618
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12619
void ImGui::NavMoveRequestApplyResult()
12620
2.41k
{
12621
2.41k
    ImGuiContext& g = *GImGui;
12622
#if IMGUI_DEBUG_NAV_SCORING
12623
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12624
        return;
12625
#endif
12626
12627
    // Select which result to use
12628
2.41k
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12629
12630
    // Tabbing forward wrap
12631
2.41k
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
12632
1.99k
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12633
161
            result = &g.NavTabbingResultFirst;
12634
12635
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12636
2.41k
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12637
2.41k
    if (result == NULL)
12638
2.23k
    {
12639
2.23k
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12640
1.83k
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12641
2.23k
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12642
12
            NavRestoreHighlightAfterMove();
12643
2.23k
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12644
2.23k
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12645
2.23k
        return;
12646
2.23k
    }
12647
12648
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12649
171
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12650
10
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12651
0
            result = &g.NavMoveResultLocalVisible;
12652
12653
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12654
171
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12655
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12656
0
            result = &g.NavMoveResultOther;
12657
171
    IM_ASSERT(g.NavWindow && result->Window);
12658
12659
    // Scroll to keep newly navigated item fully into view.
12660
171
    if (g.NavLayer == ImGuiNavLayer_Main)
12661
171
    {
12662
171
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12663
171
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12664
12665
171
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12666
0
        {
12667
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12668
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12669
0
            SetScrollY(result->Window, scroll_target);
12670
0
        }
12671
171
    }
12672
12673
171
    if (g.NavWindow != result->Window)
12674
0
    {
12675
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12676
0
        g.NavWindow = result->Window;
12677
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12678
0
    }
12679
171
    if (g.ActiveId != result->ID)
12680
171
        ClearActiveID();
12681
12682
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12683
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
12684
171
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12685
10
    {
12686
10
        g.NavJustMovedToId = result->ID;
12687
10
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12688
10
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12689
10
    }
12690
12691
    // Apply new NavID/Focus
12692
171
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12693
171
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12694
171
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12695
171
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
12696
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
12697
12698
    // Restore last preferred position for current axis
12699
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12700
171
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
12701
10
    {
12702
10
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12703
10
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12704
10
    }
12705
12706
    // Tabbing: Activates Inputable, otherwise only Focus
12707
171
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
12708
161
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
12709
12710
    // Activate
12711
171
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12712
0
    {
12713
0
        g.NavNextActivateId = result->ID;
12714
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12715
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
12716
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12717
0
    }
12718
12719
    // Enable nav highlight
12720
171
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12721
171
        NavRestoreHighlightAfterMove();
12722
171
}
12723
12724
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12725
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12726
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12727
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12728
static void ImGui::NavUpdateCancelRequest()
12729
25.7k
{
12730
25.7k
    ImGuiContext& g = *GImGui;
12731
25.7k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12732
25.7k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12733
25.7k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12734
25.6k
        return;
12735
12736
139
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12737
139
    if (g.ActiveId != 0)
12738
0
    {
12739
0
        ClearActiveID();
12740
0
    }
12741
139
    else if (g.NavLayer != ImGuiNavLayer_Main)
12742
0
    {
12743
        // Leave the "menu" layer
12744
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12745
0
        NavRestoreHighlightAfterMove();
12746
0
    }
12747
139
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12748
57
    {
12749
        // Exit child window
12750
57
        ImGuiWindow* child_window = g.NavWindow;
12751
57
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12752
57
        IM_ASSERT(child_window->ChildId != 0);
12753
57
        ImRect child_rect = child_window->Rect();
12754
57
        FocusWindow(parent_window);
12755
57
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12756
57
        NavRestoreHighlightAfterMove();
12757
57
    }
12758
82
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12759
0
    {
12760
        // Close open popup/menu
12761
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12762
0
    }
12763
82
    else
12764
82
    {
12765
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12766
82
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12767
67
            g.NavWindow->NavLastIds[0] = 0;
12768
82
        g.NavId = 0;
12769
82
    }
12770
139
}
12771
12772
// Handle PageUp/PageDown/Home/End keys
12773
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12774
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12775
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12776
static float ImGui::NavUpdatePageUpPageDown()
12777
22.7k
{
12778
22.7k
    ImGuiContext& g = *GImGui;
12779
22.7k
    ImGuiWindow* window = g.NavWindow;
12780
22.7k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12781
0
        return 0.0f;
12782
12783
22.7k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12784
22.7k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12785
22.7k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12786
22.7k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12787
22.7k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12788
13.9k
        return 0.0f;
12789
12790
8.78k
    if (g.NavLayer != ImGuiNavLayer_Main)
12791
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12792
12793
8.78k
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12794
8.69k
    {
12795
        // Fallback manual-scroll when window has no navigable item
12796
8.69k
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12797
2.29k
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12798
6.40k
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12799
26
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12800
6.37k
        else if (home_pressed)
12801
21
            SetScrollY(window, 0.0f);
12802
6.35k
        else if (end_pressed)
12803
13
            SetScrollY(window, window->ScrollMax.y);
12804
8.69k
    }
12805
93
    else
12806
93
    {
12807
93
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12808
93
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12809
93
        float nav_scoring_rect_offset_y = 0.0f;
12810
93
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12811
11
        {
12812
11
            nav_scoring_rect_offset_y = -page_offset_y;
12813
11
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12814
11
            g.NavMoveClipDir = ImGuiDir_Up;
12815
11
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12816
11
        }
12817
82
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12818
0
        {
12819
0
            nav_scoring_rect_offset_y = +page_offset_y;
12820
0
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12821
0
            g.NavMoveClipDir = ImGuiDir_Down;
12822
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
12823
0
        }
12824
82
        else if (home_pressed)
12825
0
        {
12826
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12827
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12828
            // Preserve current horizontal position if we have any.
12829
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12830
0
            if (nav_rect_rel.IsInverted())
12831
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12832
0
            g.NavMoveDir = ImGuiDir_Down;
12833
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12834
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12835
0
        }
12836
82
        else if (end_pressed)
12837
0
        {
12838
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12839
0
            if (nav_rect_rel.IsInverted())
12840
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12841
0
            g.NavMoveDir = ImGuiDir_Up;
12842
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12843
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12844
0
        }
12845
93
        return nav_scoring_rect_offset_y;
12846
93
    }
12847
8.69k
    return 0.0f;
12848
8.78k
}
12849
12850
static void ImGui::NavEndFrame()
12851
25.7k
{
12852
25.7k
    ImGuiContext& g = *GImGui;
12853
12854
    // Show CTRL+TAB list window
12855
25.7k
    if (g.NavWindowingTarget != NULL)
12856
0
        NavUpdateWindowingOverlay();
12857
12858
    // Perform wrap-around in menus
12859
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12860
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12861
25.7k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12862
0
        NavUpdateCreateWrappingRequest();
12863
25.7k
}
12864
12865
static void ImGui::NavUpdateCreateWrappingRequest()
12866
0
{
12867
0
    ImGuiContext& g = *GImGui;
12868
0
    ImGuiWindow* window = g.NavWindow;
12869
12870
0
    bool do_forward = false;
12871
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12872
0
    ImGuiDir clip_dir = g.NavMoveDir;
12873
12874
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12875
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12876
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12877
0
    {
12878
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12879
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12880
0
        {
12881
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12882
0
            clip_dir = ImGuiDir_Up;
12883
0
        }
12884
0
        do_forward = true;
12885
0
    }
12886
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12887
0
    {
12888
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12889
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12890
0
        {
12891
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12892
0
            clip_dir = ImGuiDir_Down;
12893
0
        }
12894
0
        do_forward = true;
12895
0
    }
12896
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12897
0
    {
12898
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12899
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12900
0
        {
12901
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12902
0
            clip_dir = ImGuiDir_Left;
12903
0
        }
12904
0
        do_forward = true;
12905
0
    }
12906
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12907
0
    {
12908
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12909
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12910
0
        {
12911
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12912
0
            clip_dir = ImGuiDir_Right;
12913
0
        }
12914
0
        do_forward = true;
12915
0
    }
12916
0
    if (!do_forward)
12917
0
        return;
12918
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12919
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12920
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12921
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12922
0
}
12923
12924
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12925
0
{
12926
0
    ImGuiContext& g = *GImGui;
12927
0
    IM_UNUSED(g);
12928
0
    int order = window->FocusOrder;
12929
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12930
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12931
0
    return order;
12932
0
}
12933
12934
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12935
0
{
12936
0
    ImGuiContext& g = *GImGui;
12937
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12938
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12939
0
            return g.WindowsFocusOrder[i];
12940
0
    return NULL;
12941
0
}
12942
12943
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12944
0
{
12945
0
    ImGuiContext& g = *GImGui;
12946
0
    IM_ASSERT(g.NavWindowingTarget);
12947
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12948
0
        return;
12949
12950
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12951
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12952
0
    if (!window_target)
12953
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12954
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12955
0
    {
12956
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12957
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12958
0
    }
12959
0
    g.NavWindowingToggleLayer = false;
12960
0
}
12961
12962
// Windowing management mode
12963
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12964
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12965
static void ImGui::NavUpdateWindowing()
12966
25.7k
{
12967
25.7k
    ImGuiContext& g = *GImGui;
12968
25.7k
    ImGuiIO& io = g.IO;
12969
12970
25.7k
    ImGuiWindow* apply_focus_window = NULL;
12971
25.7k
    bool apply_toggle_layer = false;
12972
12973
25.7k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12974
25.7k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
12975
25.7k
    if (!allow_windowing)
12976
0
        g.NavWindowingTarget = NULL;
12977
12978
    // Fade out
12979
25.7k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12980
0
    {
12981
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12982
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12983
0
            g.NavWindowingTargetAnim = NULL;
12984
0
    }
12985
12986
    // Start CTRL+Tab or Square+L/R window selection
12987
25.7k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12988
25.7k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12989
25.7k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12990
25.7k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12991
25.7k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12992
25.7k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12993
25.7k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12994
25.7k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12995
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12996
0
        {
12997
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12998
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12999
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13000
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13001
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13002
13003
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
13004
0
            if (keyboard_next_window || keyboard_prev_window)
13005
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13006
0
        }
13007
13008
    // Gamepad update
13009
25.7k
    g.NavWindowingTimer += io.DeltaTime;
13010
25.7k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13011
0
    {
13012
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13013
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13014
13015
        // Select window to focus
13016
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13017
0
        if (focus_change_dir != 0)
13018
0
        {
13019
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13020
0
            g.NavWindowingHighlightAlpha = 1.0f;
13021
0
        }
13022
13023
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13024
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13025
0
        {
13026
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13027
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13028
0
                apply_toggle_layer = true;
13029
0
            else if (!g.NavWindowingToggleLayer)
13030
0
                apply_focus_window = g.NavWindowingTarget;
13031
0
            g.NavWindowingTarget = NULL;
13032
0
        }
13033
0
    }
13034
13035
    // Keyboard: Focus
13036
25.7k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13037
0
    {
13038
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13039
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13040
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13041
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13042
0
        if (keyboard_next_window || keyboard_prev_window)
13043
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13044
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13045
0
            apply_focus_window = g.NavWindowingTarget;
13046
0
    }
13047
13048
    // Keyboard: Press and Release ALT to toggle menu layer
13049
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
13050
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
13051
25.7k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
13052
0
    {
13053
0
        g.NavWindowingToggleLayer = true;
13054
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
13055
0
    }
13056
25.7k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13057
0
    {
13058
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13059
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13060
        // We cancel toggling nav layer if an owner has claimed the key.
13061
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
13062
0
            g.NavWindowingToggleLayer = false;
13063
13064
        // Apply layer toggle on release
13065
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13066
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
13067
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13068
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13069
0
                    apply_toggle_layer = true;
13070
0
        if (!IsKeyDown(ImGuiMod_Alt))
13071
0
            g.NavWindowingToggleLayer = false;
13072
0
    }
13073
13074
    // Move window
13075
25.7k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13076
0
    {
13077
0
        ImVec2 nav_move_dir;
13078
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13079
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13080
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13081
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13082
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13083
0
        {
13084
0
            const float NAV_MOVE_SPEED = 800.0f;
13085
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13086
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13087
0
            g.NavDisableMouseHover = true;
13088
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13089
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13090
0
            {
13091
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13092
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13093
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13094
0
            }
13095
0
        }
13096
0
    }
13097
13098
    // Apply final focus
13099
25.7k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13100
0
    {
13101
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13102
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13103
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13104
0
        ClearActiveID();
13105
0
        NavRestoreHighlightAfterMove();
13106
0
        ClosePopupsOverWindow(apply_focus_window, false);
13107
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13108
0
        apply_focus_window = g.NavWindow;
13109
0
        if (apply_focus_window->NavLastIds[0] == 0)
13110
0
            NavInitWindow(apply_focus_window, false);
13111
13112
        // If the window has ONLY a menu layer (no main layer), select it directly
13113
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13114
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13115
        // the target window as already been previewed once.
13116
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13117
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13118
        // won't be valid.
13119
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13120
0
            g.NavLayer = ImGuiNavLayer_Menu;
13121
13122
        // Request OS level focus
13123
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13124
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13125
0
    }
13126
25.7k
    if (apply_focus_window)
13127
0
        g.NavWindowingTarget = NULL;
13128
13129
    // Apply menu/layer toggle
13130
25.7k
    if (apply_toggle_layer && g.NavWindow)
13131
0
    {
13132
0
        ClearActiveID();
13133
13134
        // Move to parent menu if necessary
13135
0
        ImGuiWindow* new_nav_window = g.NavWindow;
13136
0
        while (new_nav_window->ParentWindow
13137
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13138
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13139
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13140
0
            new_nav_window = new_nav_window->ParentWindow;
13141
0
        if (new_nav_window != g.NavWindow)
13142
0
        {
13143
0
            ImGuiWindow* old_nav_window = g.NavWindow;
13144
0
            FocusWindow(new_nav_window);
13145
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13146
0
        }
13147
13148
        // Toggle layer
13149
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13150
0
        if (new_nav_layer != g.NavLayer)
13151
0
        {
13152
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13153
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13154
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13155
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13156
0
            NavRestoreLayer(new_nav_layer);
13157
0
            NavRestoreHighlightAfterMove();
13158
0
        }
13159
0
    }
13160
25.7k
}
13161
13162
// Window has already passed the IsWindowNavFocusable()
13163
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13164
0
{
13165
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13166
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13167
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13168
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13169
0
    if (window->DockNodeAsHost)
13170
0
        return "(Dock node)"; // Not normally shown to user.
13171
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13172
0
}
13173
13174
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13175
void ImGui::NavUpdateWindowingOverlay()
13176
0
{
13177
0
    ImGuiContext& g = *GImGui;
13178
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13179
13180
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13181
0
        return;
13182
13183
0
    if (g.NavWindowingListWindow == NULL)
13184
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13185
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13186
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13187
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13188
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13189
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13190
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13191
0
    {
13192
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13193
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13194
0
        if (!IsWindowNavFocusable(window))
13195
0
            continue;
13196
0
        const char* label = window->Name;
13197
0
        if (label == FindRenderedTextEnd(label))
13198
0
            label = GetFallbackWindowNameForWindowingList(window);
13199
0
        Selectable(label, g.NavWindowingTarget == window);
13200
0
    }
13201
0
    End();
13202
0
    PopStyleVar();
13203
0
}
13204
13205
13206
//-----------------------------------------------------------------------------
13207
// [SECTION] DRAG AND DROP
13208
//-----------------------------------------------------------------------------
13209
13210
bool ImGui::IsDragDropActive()
13211
0
{
13212
0
    ImGuiContext& g = *GImGui;
13213
0
    return g.DragDropActive;
13214
0
}
13215
13216
void ImGui::ClearDragDrop()
13217
0
{
13218
0
    ImGuiContext& g = *GImGui;
13219
0
    g.DragDropActive = false;
13220
0
    g.DragDropPayload.Clear();
13221
0
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13222
0
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13223
0
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13224
0
    g.DragDropAcceptFrameCount = -1;
13225
13226
0
    g.DragDropPayloadBufHeap.clear();
13227
0
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13228
0
}
13229
13230
bool ImGui::BeginTooltipHidden()
13231
0
{
13232
0
    ImGuiContext& g = *GImGui;
13233
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13234
0
    SetWindowHiddendAndSkipItemsForCurrentFrame(g.CurrentWindow);
13235
0
    return ret;
13236
0
}
13237
13238
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13239
// If the item has an identifier:
13240
// - This assume/require the item to be activated (typically via ButtonBehavior).
13241
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13242
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13243
// If the item has no identifier:
13244
// - Currently always assume left mouse button.
13245
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13246
0
{
13247
0
    ImGuiContext& g = *GImGui;
13248
0
    ImGuiWindow* window = g.CurrentWindow;
13249
13250
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13251
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13252
0
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13253
13254
0
    bool source_drag_active = false;
13255
0
    ImGuiID source_id = 0;
13256
0
    ImGuiID source_parent_id = 0;
13257
0
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
13258
0
    {
13259
0
        source_id = g.LastItemData.ID;
13260
0
        if (source_id != 0)
13261
0
        {
13262
            // Common path: items with ID
13263
0
            if (g.ActiveId != source_id)
13264
0
                return false;
13265
0
            if (g.ActiveIdMouseButton != -1)
13266
0
                mouse_button = g.ActiveIdMouseButton;
13267
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13268
0
                return false;
13269
0
            g.ActiveIdAllowOverlap = false;
13270
0
        }
13271
0
        else
13272
0
        {
13273
            // Uncommon path: items without ID
13274
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13275
0
                return false;
13276
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13277
0
                return false;
13278
13279
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13280
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13281
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13282
0
            {
13283
0
                IM_ASSERT(0);
13284
0
                return false;
13285
0
            }
13286
13287
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13288
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13289
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13290
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13291
            // Rely on keeping other window->LastItemXXX fields intact.
13292
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13293
0
            KeepAliveID(source_id);
13294
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13295
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13296
0
            {
13297
0
                SetActiveID(source_id, window);
13298
0
                FocusWindow(window);
13299
0
            }
13300
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13301
0
                g.ActiveIdAllowOverlap = is_hovered;
13302
0
        }
13303
0
        if (g.ActiveId != source_id)
13304
0
            return false;
13305
0
        source_parent_id = window->IDStack.back();
13306
0
        source_drag_active = IsMouseDragging(mouse_button);
13307
13308
        // Disable navigation and key inputs while dragging + cancel existing request if any
13309
0
        SetActiveIdUsingAllKeyboardKeys();
13310
0
    }
13311
0
    else
13312
0
    {
13313
0
        window = NULL;
13314
0
        source_id = ImHashStr("#SourceExtern");
13315
0
        source_drag_active = true;
13316
0
    }
13317
13318
0
    if (source_drag_active)
13319
0
    {
13320
0
        if (!g.DragDropActive)
13321
0
        {
13322
0
            IM_ASSERT(source_id != 0);
13323
0
            ClearDragDrop();
13324
0
            ImGuiPayload& payload = g.DragDropPayload;
13325
0
            payload.SourceId = source_id;
13326
0
            payload.SourceParentId = source_parent_id;
13327
0
            g.DragDropActive = true;
13328
0
            g.DragDropSourceFlags = flags;
13329
0
            g.DragDropMouseButton = mouse_button;
13330
0
            if (payload.SourceId == g.ActiveId)
13331
0
                g.ActiveIdNoClearOnFocusLoss = true;
13332
0
        }
13333
0
        g.DragDropSourceFrameCount = g.FrameCount;
13334
0
        g.DragDropWithinSource = true;
13335
13336
0
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13337
0
        {
13338
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13339
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13340
0
            bool ret;
13341
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13342
0
                ret = BeginTooltipHidden();
13343
0
            else
13344
0
                ret = BeginTooltip();
13345
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13346
0
            IM_UNUSED(ret);
13347
0
        }
13348
13349
0
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13350
0
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13351
13352
0
        return true;
13353
0
    }
13354
0
    return false;
13355
0
}
13356
13357
void ImGui::EndDragDropSource()
13358
0
{
13359
0
    ImGuiContext& g = *GImGui;
13360
0
    IM_ASSERT(g.DragDropActive);
13361
0
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13362
13363
0
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13364
0
        EndTooltip();
13365
13366
    // Discard the drag if have not called SetDragDropPayload()
13367
0
    if (g.DragDropPayload.DataFrameCount == -1)
13368
0
        ClearDragDrop();
13369
0
    g.DragDropWithinSource = false;
13370
0
}
13371
13372
// Use 'cond' to choose to submit payload on drag start or every frame
13373
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13374
0
{
13375
0
    ImGuiContext& g = *GImGui;
13376
0
    ImGuiPayload& payload = g.DragDropPayload;
13377
0
    if (cond == 0)
13378
0
        cond = ImGuiCond_Always;
13379
13380
0
    IM_ASSERT(type != NULL);
13381
0
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13382
0
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13383
0
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13384
0
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13385
13386
0
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13387
0
    {
13388
        // Copy payload
13389
0
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13390
0
        g.DragDropPayloadBufHeap.resize(0);
13391
0
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13392
0
        {
13393
            // Store in heap
13394
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13395
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13396
0
            memcpy(payload.Data, data, data_size);
13397
0
        }
13398
0
        else if (data_size > 0)
13399
0
        {
13400
            // Store locally
13401
0
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13402
0
            payload.Data = g.DragDropPayloadBufLocal;
13403
0
            memcpy(payload.Data, data, data_size);
13404
0
        }
13405
0
        else
13406
0
        {
13407
0
            payload.Data = NULL;
13408
0
        }
13409
0
        payload.DataSize = (int)data_size;
13410
0
    }
13411
0
    payload.DataFrameCount = g.FrameCount;
13412
13413
    // Return whether the payload has been accepted
13414
0
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13415
0
}
13416
13417
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13418
0
{
13419
0
    ImGuiContext& g = *GImGui;
13420
0
    if (!g.DragDropActive)
13421
0
        return false;
13422
13423
0
    ImGuiWindow* window = g.CurrentWindow;
13424
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13425
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13426
0
        return false;
13427
0
    IM_ASSERT(id != 0);
13428
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13429
0
        return false;
13430
0
    if (window->SkipItems)
13431
0
        return false;
13432
13433
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13434
0
    g.DragDropTargetRect = bb;
13435
0
    g.DragDropTargetId = id;
13436
0
    g.DragDropWithinTarget = true;
13437
0
    return true;
13438
0
}
13439
13440
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13441
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13442
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13443
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13444
bool ImGui::BeginDragDropTarget()
13445
0
{
13446
0
    ImGuiContext& g = *GImGui;
13447
0
    if (!g.DragDropActive)
13448
0
        return false;
13449
13450
0
    ImGuiWindow* window = g.CurrentWindow;
13451
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13452
0
        return false;
13453
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13454
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13455
0
        return false;
13456
13457
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13458
0
    ImGuiID id = g.LastItemData.ID;
13459
0
    if (id == 0)
13460
0
    {
13461
0
        id = window->GetIDFromRectangle(display_rect);
13462
0
        KeepAliveID(id);
13463
0
    }
13464
0
    if (g.DragDropPayload.SourceId == id)
13465
0
        return false;
13466
13467
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13468
0
    g.DragDropTargetRect = display_rect;
13469
0
    g.DragDropTargetId = id;
13470
0
    g.DragDropWithinTarget = true;
13471
0
    return true;
13472
0
}
13473
13474
bool ImGui::IsDragDropPayloadBeingAccepted()
13475
0
{
13476
0
    ImGuiContext& g = *GImGui;
13477
0
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13478
0
}
13479
13480
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13481
0
{
13482
0
    ImGuiContext& g = *GImGui;
13483
0
    ImGuiPayload& payload = g.DragDropPayload;
13484
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13485
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13486
0
    if (type != NULL && !payload.IsDataType(type))
13487
0
        return NULL;
13488
13489
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13490
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13491
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13492
0
    ImRect r = g.DragDropTargetRect;
13493
0
    float r_surface = r.GetWidth() * r.GetHeight();
13494
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13495
0
        return NULL;
13496
13497
0
    g.DragDropAcceptFlags = flags;
13498
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13499
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13500
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13501
13502
    // Render default drop visuals
13503
0
    payload.Preview = was_accepted_previously;
13504
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13505
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13506
0
        RenderDragDropTargetRect(r);
13507
13508
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13509
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13510
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13511
0
        return NULL;
13512
13513
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13514
0
    return &payload;
13515
0
}
13516
13517
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13518
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
13519
0
{
13520
0
    ImGuiContext& g = *GImGui;
13521
0
    ImGuiWindow* window = g.CurrentWindow;
13522
0
    ImRect bb_display = bb;
13523
0
    bb_display.ClipWith(window->ClipRect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
13524
0
    bb_display.Expand(3.5f);
13525
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
13526
0
    if (push_clip_rect)
13527
0
        window->DrawList->PushClipRectFullScreen();
13528
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13529
0
    if (push_clip_rect)
13530
0
        window->DrawList->PopClipRect();
13531
0
}
13532
13533
const ImGuiPayload* ImGui::GetDragDropPayload()
13534
0
{
13535
0
    ImGuiContext& g = *GImGui;
13536
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13537
0
}
13538
13539
void ImGui::EndDragDropTarget()
13540
0
{
13541
0
    ImGuiContext& g = *GImGui;
13542
0
    IM_ASSERT(g.DragDropActive);
13543
0
    IM_ASSERT(g.DragDropWithinTarget);
13544
0
    g.DragDropWithinTarget = false;
13545
13546
    // Clear drag and drop state payload right after delivery
13547
0
    if (g.DragDropPayload.Delivery)
13548
0
        ClearDragDrop();
13549
0
}
13550
13551
//-----------------------------------------------------------------------------
13552
// [SECTION] LOGGING/CAPTURING
13553
//-----------------------------------------------------------------------------
13554
// All text output from the interface can be captured into tty/file/clipboard.
13555
// By default, tree nodes are automatically opened during logging.
13556
//-----------------------------------------------------------------------------
13557
13558
// Pass text data straight to log (without being displayed)
13559
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13560
0
{
13561
0
    if (g.LogFile)
13562
0
    {
13563
0
        g.LogBuffer.Buf.resize(0);
13564
0
        g.LogBuffer.appendfv(fmt, args);
13565
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13566
0
    }
13567
0
    else
13568
0
    {
13569
0
        g.LogBuffer.appendfv(fmt, args);
13570
0
    }
13571
0
}
13572
13573
void ImGui::LogText(const char* fmt, ...)
13574
0
{
13575
0
    ImGuiContext& g = *GImGui;
13576
0
    if (!g.LogEnabled)
13577
0
        return;
13578
13579
0
    va_list args;
13580
0
    va_start(args, fmt);
13581
0
    LogTextV(g, fmt, args);
13582
0
    va_end(args);
13583
0
}
13584
13585
void ImGui::LogTextV(const char* fmt, va_list args)
13586
0
{
13587
0
    ImGuiContext& g = *GImGui;
13588
0
    if (!g.LogEnabled)
13589
0
        return;
13590
13591
0
    LogTextV(g, fmt, args);
13592
0
}
13593
13594
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13595
// We split text into individual lines to add current tree level padding
13596
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13597
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13598
0
{
13599
0
    ImGuiContext& g = *GImGui;
13600
0
    ImGuiWindow* window = g.CurrentWindow;
13601
13602
0
    const char* prefix = g.LogNextPrefix;
13603
0
    const char* suffix = g.LogNextSuffix;
13604
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13605
13606
0
    if (!text_end)
13607
0
        text_end = FindRenderedTextEnd(text, text_end);
13608
13609
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13610
0
    if (ref_pos)
13611
0
        g.LogLinePosY = ref_pos->y;
13612
0
    if (log_new_line)
13613
0
    {
13614
0
        LogText(IM_NEWLINE);
13615
0
        g.LogLineFirstItem = true;
13616
0
    }
13617
13618
0
    if (prefix)
13619
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13620
13621
    // Re-adjust padding if we have popped out of our starting depth
13622
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13623
0
        g.LogDepthRef = window->DC.TreeDepth;
13624
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13625
13626
0
    const char* text_remaining = text;
13627
0
    for (;;)
13628
0
    {
13629
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13630
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13631
0
        const char* line_start = text_remaining;
13632
0
        const char* line_end = ImStreolRange(line_start, text_end);
13633
0
        const bool is_last_line = (line_end == text_end);
13634
0
        if (line_start != line_end || !is_last_line)
13635
0
        {
13636
0
            const int line_length = (int)(line_end - line_start);
13637
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13638
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13639
0
            g.LogLineFirstItem = false;
13640
0
            if (*line_end == '\n')
13641
0
            {
13642
0
                LogText(IM_NEWLINE);
13643
0
                g.LogLineFirstItem = true;
13644
0
            }
13645
0
        }
13646
0
        if (is_last_line)
13647
0
            break;
13648
0
        text_remaining = line_end + 1;
13649
0
    }
13650
13651
0
    if (suffix)
13652
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13653
0
}
13654
13655
// Start logging/capturing text output
13656
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13657
0
{
13658
0
    ImGuiContext& g = *GImGui;
13659
0
    ImGuiWindow* window = g.CurrentWindow;
13660
0
    IM_ASSERT(g.LogEnabled == false);
13661
0
    IM_ASSERT(g.LogFile == NULL);
13662
0
    IM_ASSERT(g.LogBuffer.empty());
13663
0
    g.LogEnabled = true;
13664
0
    g.LogType = type;
13665
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13666
0
    g.LogDepthRef = window->DC.TreeDepth;
13667
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13668
0
    g.LogLinePosY = FLT_MAX;
13669
0
    g.LogLineFirstItem = true;
13670
0
}
13671
13672
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13673
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13674
0
{
13675
0
    ImGuiContext& g = *GImGui;
13676
0
    g.LogNextPrefix = prefix;
13677
0
    g.LogNextSuffix = suffix;
13678
0
}
13679
13680
void ImGui::LogToTTY(int auto_open_depth)
13681
0
{
13682
0
    ImGuiContext& g = *GImGui;
13683
0
    if (g.LogEnabled)
13684
0
        return;
13685
0
    IM_UNUSED(auto_open_depth);
13686
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13687
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13688
0
    g.LogFile = stdout;
13689
0
#endif
13690
0
}
13691
13692
// Start logging/capturing text output to given file
13693
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13694
0
{
13695
0
    ImGuiContext& g = *GImGui;
13696
0
    if (g.LogEnabled)
13697
0
        return;
13698
13699
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13700
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13701
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13702
0
    if (!filename)
13703
0
        filename = g.IO.LogFilename;
13704
0
    if (!filename || !filename[0])
13705
0
        return;
13706
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13707
0
    if (!f)
13708
0
    {
13709
0
        IM_ASSERT(0);
13710
0
        return;
13711
0
    }
13712
13713
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13714
0
    g.LogFile = f;
13715
0
}
13716
13717
// Start logging/capturing text output to clipboard
13718
void ImGui::LogToClipboard(int auto_open_depth)
13719
0
{
13720
0
    ImGuiContext& g = *GImGui;
13721
0
    if (g.LogEnabled)
13722
0
        return;
13723
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13724
0
}
13725
13726
void ImGui::LogToBuffer(int auto_open_depth)
13727
0
{
13728
0
    ImGuiContext& g = *GImGui;
13729
0
    if (g.LogEnabled)
13730
0
        return;
13731
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13732
0
}
13733
13734
void ImGui::LogFinish()
13735
51.5k
{
13736
51.5k
    ImGuiContext& g = *GImGui;
13737
51.5k
    if (!g.LogEnabled)
13738
51.5k
        return;
13739
13740
0
    LogText(IM_NEWLINE);
13741
0
    switch (g.LogType)
13742
0
    {
13743
0
    case ImGuiLogType_TTY:
13744
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13745
0
        fflush(g.LogFile);
13746
0
#endif
13747
0
        break;
13748
0
    case ImGuiLogType_File:
13749
0
        ImFileClose(g.LogFile);
13750
0
        break;
13751
0
    case ImGuiLogType_Buffer:
13752
0
        break;
13753
0
    case ImGuiLogType_Clipboard:
13754
0
        if (!g.LogBuffer.empty())
13755
0
            SetClipboardText(g.LogBuffer.begin());
13756
0
        break;
13757
0
    case ImGuiLogType_None:
13758
0
        IM_ASSERT(0);
13759
0
        break;
13760
0
    }
13761
13762
0
    g.LogEnabled = false;
13763
0
    g.LogType = ImGuiLogType_None;
13764
0
    g.LogFile = NULL;
13765
0
    g.LogBuffer.clear();
13766
0
}
13767
13768
// Helper to display logging buttons
13769
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13770
void ImGui::LogButtons()
13771
0
{
13772
0
    ImGuiContext& g = *GImGui;
13773
13774
0
    PushID("LogButtons");
13775
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13776
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13777
#else
13778
    const bool log_to_tty = false;
13779
#endif
13780
0
    const bool log_to_file = Button("Log To File"); SameLine();
13781
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13782
0
    PushTabStop(false);
13783
0
    SetNextItemWidth(80.0f);
13784
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13785
0
    PopTabStop();
13786
0
    PopID();
13787
13788
    // Start logging at the end of the function so that the buttons don't appear in the log
13789
0
    if (log_to_tty)
13790
0
        LogToTTY();
13791
0
    if (log_to_file)
13792
0
        LogToFile();
13793
0
    if (log_to_clipboard)
13794
0
        LogToClipboard();
13795
0
}
13796
13797
13798
//-----------------------------------------------------------------------------
13799
// [SECTION] SETTINGS
13800
//-----------------------------------------------------------------------------
13801
// - UpdateSettings() [Internal]
13802
// - MarkIniSettingsDirty() [Internal]
13803
// - FindSettingsHandler() [Internal]
13804
// - ClearIniSettings() [Internal]
13805
// - LoadIniSettingsFromDisk()
13806
// - LoadIniSettingsFromMemory()
13807
// - SaveIniSettingsToDisk()
13808
// - SaveIniSettingsToMemory()
13809
//-----------------------------------------------------------------------------
13810
// - CreateNewWindowSettings() [Internal]
13811
// - FindWindowSettingsByID() [Internal]
13812
// - FindWindowSettingsByWindow() [Internal]
13813
// - ClearWindowSettings() [Internal]
13814
// - WindowSettingsHandler_***() [Internal]
13815
//-----------------------------------------------------------------------------
13816
13817
// Called by NewFrame()
13818
void ImGui::UpdateSettings()
13819
25.7k
{
13820
    // Load settings on first frame (if not explicitly loaded manually before)
13821
25.7k
    ImGuiContext& g = *GImGui;
13822
25.7k
    if (!g.SettingsLoaded)
13823
1
    {
13824
1
        IM_ASSERT(g.SettingsWindows.empty());
13825
1
        if (g.IO.IniFilename)
13826
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13827
1
        g.SettingsLoaded = true;
13828
1
    }
13829
13830
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13831
25.7k
    if (g.SettingsDirtyTimer > 0.0f)
13832
300
    {
13833
300
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13834
300
        if (g.SettingsDirtyTimer <= 0.0f)
13835
1
        {
13836
1
            if (g.IO.IniFilename != NULL)
13837
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13838
1
            else
13839
1
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13840
1
            g.SettingsDirtyTimer = 0.0f;
13841
1
        }
13842
300
    }
13843
25.7k
}
13844
13845
void ImGui::MarkIniSettingsDirty()
13846
0
{
13847
0
    ImGuiContext& g = *GImGui;
13848
0
    if (g.SettingsDirtyTimer <= 0.0f)
13849
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13850
0
}
13851
13852
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13853
25.3k
{
13854
25.3k
    ImGuiContext& g = *GImGui;
13855
25.3k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13856
3
        if (g.SettingsDirtyTimer <= 0.0f)
13857
1
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13858
25.3k
}
13859
13860
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13861
2
{
13862
2
    ImGuiContext& g = *GImGui;
13863
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13864
2
    g.SettingsHandlers.push_back(*handler);
13865
2
}
13866
13867
void ImGui::RemoveSettingsHandler(const char* type_name)
13868
0
{
13869
0
    ImGuiContext& g = *GImGui;
13870
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13871
0
        g.SettingsHandlers.erase(handler);
13872
0
}
13873
13874
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13875
2
{
13876
2
    ImGuiContext& g = *GImGui;
13877
2
    const ImGuiID type_hash = ImHashStr(type_name);
13878
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13879
1
        if (handler.TypeHash == type_hash)
13880
0
            return &handler;
13881
2
    return NULL;
13882
2
}
13883
13884
// Clear all settings (windows, tables, docking etc.)
13885
void ImGui::ClearIniSettings()
13886
0
{
13887
0
    ImGuiContext& g = *GImGui;
13888
0
    g.SettingsIniData.clear();
13889
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13890
0
        if (handler.ClearAllFn != NULL)
13891
0
            handler.ClearAllFn(&g, &handler);
13892
0
}
13893
13894
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13895
0
{
13896
0
    size_t file_data_size = 0;
13897
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13898
0
    if (!file_data)
13899
0
        return;
13900
0
    if (file_data_size > 0)
13901
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13902
0
    IM_FREE(file_data);
13903
0
}
13904
13905
// Zero-tolerance, no error reporting, cheap .ini parsing
13906
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
13907
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13908
0
{
13909
0
    ImGuiContext& g = *GImGui;
13910
0
    IM_ASSERT(g.Initialized);
13911
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13912
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13913
13914
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13915
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13916
0
    if (ini_size == 0)
13917
0
        ini_size = strlen(ini_data);
13918
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13919
0
    char* const buf = g.SettingsIniData.Buf.Data;
13920
0
    char* const buf_end = buf + ini_size;
13921
0
    memcpy(buf, ini_data, ini_size);
13922
0
    buf_end[0] = 0;
13923
13924
    // Call pre-read handlers
13925
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13926
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13927
0
        if (handler.ReadInitFn != NULL)
13928
0
            handler.ReadInitFn(&g, &handler);
13929
13930
0
    void* entry_data = NULL;
13931
0
    ImGuiSettingsHandler* entry_handler = NULL;
13932
13933
0
    char* line_end = NULL;
13934
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13935
0
    {
13936
        // Skip new lines markers, then find end of the line
13937
0
        while (*line == '\n' || *line == '\r')
13938
0
            line++;
13939
0
        line_end = line;
13940
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13941
0
            line_end++;
13942
0
        line_end[0] = 0;
13943
0
        if (line[0] == ';')
13944
0
            continue;
13945
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13946
0
        {
13947
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13948
0
            line_end[-1] = 0;
13949
0
            const char* name_end = line_end - 1;
13950
0
            const char* type_start = line + 1;
13951
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13952
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13953
0
            if (!type_end || !name_start)
13954
0
                continue;
13955
0
            *type_end = 0; // Overwrite first ']'
13956
0
            name_start++;  // Skip second '['
13957
0
            entry_handler = FindSettingsHandler(type_start);
13958
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13959
0
        }
13960
0
        else if (entry_handler != NULL && entry_data != NULL)
13961
0
        {
13962
            // Let type handler parse the line
13963
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13964
0
        }
13965
0
    }
13966
0
    g.SettingsLoaded = true;
13967
13968
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13969
0
    memcpy(buf, ini_data, ini_size);
13970
13971
    // Call post-read handlers
13972
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
13973
0
        if (handler.ApplyAllFn != NULL)
13974
0
            handler.ApplyAllFn(&g, &handler);
13975
0
}
13976
13977
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13978
0
{
13979
0
    ImGuiContext& g = *GImGui;
13980
0
    g.SettingsDirtyTimer = 0.0f;
13981
0
    if (!ini_filename)
13982
0
        return;
13983
13984
0
    size_t ini_data_size = 0;
13985
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13986
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13987
0
    if (!f)
13988
0
        return;
13989
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13990
0
    ImFileClose(f);
13991
0
}
13992
13993
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13994
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13995
0
{
13996
0
    ImGuiContext& g = *GImGui;
13997
0
    g.SettingsDirtyTimer = 0.0f;
13998
0
    g.SettingsIniData.Buf.resize(0);
13999
0
    g.SettingsIniData.Buf.push_back(0);
14000
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14001
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14002
0
    if (out_size)
14003
0
        *out_size = (size_t)g.SettingsIniData.size();
14004
0
    return g.SettingsIniData.c_str();
14005
0
}
14006
14007
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14008
0
{
14009
0
    ImGuiContext& g = *GImGui;
14010
14011
0
    if (g.IO.ConfigDebugIniSettings == false)
14012
0
    {
14013
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14014
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14015
0
        if (const char* p = strstr(name, "###"))
14016
0
            name = p;
14017
0
    }
14018
0
    const size_t name_len = strlen(name);
14019
14020
    // Allocate chunk
14021
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14022
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14023
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14024
0
    settings->ID = ImHashStr(name, name_len);
14025
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14026
14027
0
    return settings;
14028
0
}
14029
14030
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14031
// This is called once per window .ini entry + once per newly instantiated window.
14032
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14033
2
{
14034
2
    ImGuiContext& g = *GImGui;
14035
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14036
0
        if (settings->ID == id && !settings->WantDelete)
14037
0
            return settings;
14038
2
    return NULL;
14039
2
}
14040
14041
// This is faster if you are holding on a Window already as we don't need to perform a search.
14042
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14043
2
{
14044
2
    ImGuiContext& g = *GImGui;
14045
2
    if (window->SettingsOffset != -1)
14046
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14047
2
    return FindWindowSettingsByID(window->ID);
14048
2
}
14049
14050
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14051
void ImGui::ClearWindowSettings(const char* name)
14052
0
{
14053
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14054
0
    ImGuiContext& g = *GImGui;
14055
0
    ImGuiWindow* window = FindWindowByName(name);
14056
0
    if (window != NULL)
14057
0
    {
14058
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14059
0
        InitOrLoadWindowSettings(window, NULL);
14060
0
        if (window->DockId != 0)
14061
0
            DockContextProcessUndockWindow(&g, window, true);
14062
0
    }
14063
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14064
0
        settings->WantDelete = true;
14065
0
}
14066
14067
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14068
0
{
14069
0
    ImGuiContext& g = *ctx;
14070
0
    for (ImGuiWindow* window : g.Windows)
14071
0
        window->SettingsOffset = -1;
14072
0
    g.SettingsWindows.clear();
14073
0
}
14074
14075
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14076
0
{
14077
0
    ImGuiID id = ImHashStr(name);
14078
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14079
0
    if (settings)
14080
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14081
0
    else
14082
0
        settings = ImGui::CreateNewWindowSettings(name);
14083
0
    settings->ID = id;
14084
0
    settings->WantApply = true;
14085
0
    return (void*)settings;
14086
0
}
14087
14088
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14089
0
{
14090
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14091
0
    int x, y;
14092
0
    int i;
14093
0
    ImU32 u1;
14094
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14095
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14096
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14097
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14098
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14099
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14100
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14101
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14102
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14103
0
}
14104
14105
// Apply to existing windows (if any)
14106
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14107
0
{
14108
0
    ImGuiContext& g = *ctx;
14109
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14110
0
        if (settings->WantApply)
14111
0
        {
14112
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14113
0
                ApplyWindowSettings(window, settings);
14114
0
            settings->WantApply = false;
14115
0
        }
14116
0
}
14117
14118
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14119
0
{
14120
    // Gather data from windows that were active during this session
14121
    // (if a window wasn't opened in this session we preserve its settings)
14122
0
    ImGuiContext& g = *ctx;
14123
0
    for (ImGuiWindow* window : g.Windows)
14124
0
    {
14125
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14126
0
            continue;
14127
14128
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14129
0
        if (!settings)
14130
0
        {
14131
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14132
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14133
0
        }
14134
0
        IM_ASSERT(settings->ID == window->ID);
14135
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14136
0
        settings->Size = ImVec2ih(window->SizeFull);
14137
0
        settings->ViewportId = window->ViewportId;
14138
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14139
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14140
0
        settings->DockId = window->DockId;
14141
0
        settings->ClassId = window->WindowClass.ClassId;
14142
0
        settings->DockOrder = window->DockOrder;
14143
0
        settings->Collapsed = window->Collapsed;
14144
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14145
0
        settings->WantDelete = false;
14146
0
    }
14147
14148
    // Write to text buffer
14149
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14150
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14151
0
    {
14152
0
        if (settings->WantDelete)
14153
0
            continue;
14154
0
        const char* settings_name = settings->GetName();
14155
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14156
0
        if (settings->IsChild)
14157
0
        {
14158
0
            buf->appendf("IsChild=1\n");
14159
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14160
0
        }
14161
0
        else
14162
0
        {
14163
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14164
0
            {
14165
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14166
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14167
0
            }
14168
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14169
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14170
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14171
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14172
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14173
0
            if (settings->DockId != 0)
14174
0
            {
14175
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14176
0
                if (settings->DockOrder == -1)
14177
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14178
0
                else
14179
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14180
0
                if (settings->ClassId != 0)
14181
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14182
0
            }
14183
0
        }
14184
0
        buf->append("\n");
14185
0
    }
14186
0
}
14187
14188
14189
//-----------------------------------------------------------------------------
14190
// [SECTION] LOCALIZATION
14191
//-----------------------------------------------------------------------------
14192
14193
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14194
1
{
14195
1
    ImGuiContext& g = *GImGui;
14196
12
    for (int n = 0; n < count; n++)
14197
11
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14198
1
}
14199
14200
14201
//-----------------------------------------------------------------------------
14202
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14203
//-----------------------------------------------------------------------------
14204
// - GetMainViewport()
14205
// - FindViewportByID()
14206
// - FindViewportByPlatformHandle()
14207
// - SetCurrentViewport() [Internal]
14208
// - SetWindowViewport() [Internal]
14209
// - GetWindowAlwaysWantOwnViewport() [Internal]
14210
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14211
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14212
// - TranslateWindowsInViewport() [Internal]
14213
// - ScaleWindowsInViewport() [Internal]
14214
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14215
// - UpdateViewportsNewFrame() [Internal]
14216
// - UpdateViewportsEndFrame() [Internal]
14217
// - AddUpdateViewport() [Internal]
14218
// - WindowSelectViewport() [Internal]
14219
// - WindowSyncOwnedViewport() [Internal]
14220
// - UpdatePlatformWindows()
14221
// - RenderPlatformWindowsDefault()
14222
// - FindPlatformMonitorForPos() [Internal]
14223
// - FindPlatformMonitorForRect() [Internal]
14224
// - UpdateViewportPlatformMonitor() [Internal]
14225
// - DestroyPlatformWindow() [Internal]
14226
// - DestroyPlatformWindows()
14227
//-----------------------------------------------------------------------------
14228
14229
ImGuiViewport* ImGui::GetMainViewport()
14230
77.3k
{
14231
77.3k
    ImGuiContext& g = *GImGui;
14232
77.3k
    return g.Viewports[0];
14233
77.3k
}
14234
14235
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14236
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14237
25.7k
{
14238
25.7k
    ImGuiContext& g = *GImGui;
14239
25.7k
    for (ImGuiViewportP* viewport : g.Viewports)
14240
25.7k
        if (viewport->ID == id)
14241
25.7k
            return viewport;
14242
0
    return NULL;
14243
25.7k
}
14244
14245
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14246
0
{
14247
0
    ImGuiContext& g = *GImGui;
14248
0
    for (ImGuiViewportP* viewport : g.Viewports)
14249
0
        if (viewport->PlatformHandle == platform_handle)
14250
0
            return viewport;
14251
0
    return NULL;
14252
0
}
14253
14254
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14255
154k
{
14256
154k
    ImGuiContext& g = *GImGui;
14257
154k
    (void)current_window;
14258
14259
154k
    if (viewport)
14260
128k
        viewport->LastFrameActive = g.FrameCount;
14261
154k
    if (g.CurrentViewport == viewport)
14262
103k
        return;
14263
51.5k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14264
51.5k
    g.CurrentViewport = viewport;
14265
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14266
14267
    // Notify platform layer of viewport changes
14268
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14269
51.5k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14270
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14271
51.5k
}
14272
14273
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14274
77.3k
{
14275
    // Abandon viewport
14276
77.3k
    if (window->ViewportOwned && window->Viewport->Window == window)
14277
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14278
14279
77.3k
    window->Viewport = viewport;
14280
77.3k
    window->ViewportId = viewport->ID;
14281
77.3k
    window->ViewportOwned = (viewport->Window == window);
14282
77.3k
}
14283
14284
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14285
0
{
14286
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14287
0
    ImGuiContext& g = *GImGui;
14288
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14289
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14290
0
            if (!window->DockIsActive)
14291
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14292
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14293
0
                        return true;
14294
0
    return false;
14295
0
}
14296
14297
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14298
0
{
14299
0
    ImGuiContext& g = *GImGui;
14300
0
    if (window->Viewport == viewport)
14301
0
        return false;
14302
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14303
0
        return false;
14304
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14305
0
        return false;
14306
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14307
0
        return false;
14308
0
    if (GetWindowAlwaysWantOwnViewport(window))
14309
0
        return false;
14310
14311
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14312
0
    for (ImGuiWindow* window_behind : g.Windows)
14313
0
    {
14314
0
        if (window_behind == window)
14315
0
            break;
14316
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14317
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14318
0
                return false;
14319
0
    }
14320
14321
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14322
0
    ImGuiViewportP* old_viewport = window->Viewport;
14323
0
    if (window->ViewportOwned)
14324
0
        for (int n = 0; n < g.Windows.Size; n++)
14325
0
            if (g.Windows[n]->Viewport == old_viewport)
14326
0
                SetWindowViewport(g.Windows[n], viewport);
14327
0
    SetWindowViewport(window, viewport);
14328
0
    BringWindowToDisplayFront(window);
14329
14330
0
    return true;
14331
0
}
14332
14333
// FIXME: handle 0 to N host viewports
14334
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14335
0
{
14336
0
    ImGuiContext& g = *GImGui;
14337
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14338
0
}
14339
14340
// Translate Dear ImGui windows when a Host Viewport has been moved
14341
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14342
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14343
0
{
14344
0
    ImGuiContext& g = *GImGui;
14345
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14346
14347
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14348
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14349
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
14350
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
14351
    // and so the window will appear to teleport when releasing the mouse.
14352
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14353
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14354
0
    ImVec2 delta_pos = new_pos - old_pos;
14355
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
14356
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
14357
0
            TranslateWindow(window, delta_pos);
14358
0
}
14359
14360
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14361
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14362
0
{
14363
0
    ImGuiContext& g = *GImGui;
14364
0
    if (viewport->Window)
14365
0
    {
14366
0
        ScaleWindow(viewport->Window, scale);
14367
0
    }
14368
0
    else
14369
0
    {
14370
0
        for (ImGuiWindow* window : g.Windows)
14371
0
            if (window->Viewport == viewport)
14372
0
                ScaleWindow(window, scale);
14373
0
    }
14374
0
}
14375
14376
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14377
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14378
// B) It requires Platform_GetWindowFocus to be implemented by backend.
14379
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14380
0
{
14381
0
    ImGuiContext& g = *GImGui;
14382
0
    ImGuiViewportP* best_candidate = NULL;
14383
0
    for (ImGuiViewportP* viewport : g.Viewports)
14384
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14385
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14386
0
                best_candidate = viewport;
14387
0
    return best_candidate;
14388
0
}
14389
14390
// Update viewports and monitor infos
14391
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14392
static void ImGui::UpdateViewportsNewFrame()
14393
25.7k
{
14394
25.7k
    ImGuiContext& g = *GImGui;
14395
25.7k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14396
14397
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14398
    // Update Focused status
14399
25.7k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14400
25.7k
    if (viewports_enabled)
14401
0
    {
14402
0
        ImGuiViewportP* focused_viewport = NULL;
14403
0
        for (ImGuiViewportP* viewport : g.Viewports)
14404
0
        {
14405
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14406
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14407
0
            {
14408
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14409
0
                if (is_minimized)
14410
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14411
0
                else
14412
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14413
0
            }
14414
14415
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14416
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14417
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14418
0
            {
14419
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14420
0
                if (is_focused)
14421
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14422
0
                else
14423
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14424
0
                if (is_focused)
14425
0
                    focused_viewport = viewport;
14426
0
            }
14427
0
        }
14428
14429
        // Focused viewport has changed?
14430
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14431
0
        {
14432
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14433
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14434
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14435
14436
            // Store a tag so we can infer z-order easily from all our windows
14437
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14438
            // will keep the front most stamp instead of losing it back to their parent viewport.
14439
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14440
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14441
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14442
14443
            // Focus associated dear imgui window
14444
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14445
            // - if focus didn't happen because we destroyed another window (#6462)
14446
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14447
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14448
0
            if (apply_imgui_focus_on_focused_viewport)
14449
0
            {
14450
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14451
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14452
0
                if (focused_viewport->Window != NULL)
14453
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14454
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14455
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14456
0
                else
14457
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14458
0
            }
14459
0
        }
14460
0
        if (focused_viewport)
14461
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14462
0
    }
14463
14464
    // Create/update main viewport with current platform position.
14465
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14466
25.7k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14467
25.7k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14468
25.7k
    IM_ASSERT(main_viewport->Window == NULL);
14469
25.7k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14470
25.7k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14471
25.7k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14472
0
    {
14473
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14474
0
        main_viewport_size = main_viewport->Size;
14475
0
    }
14476
25.7k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14477
14478
25.7k
    g.CurrentDpiScale = 0.0f;
14479
25.7k
    g.CurrentViewport = NULL;
14480
25.7k
    g.MouseViewport = NULL;
14481
51.5k
    for (int n = 0; n < g.Viewports.Size; n++)
14482
25.7k
    {
14483
25.7k
        ImGuiViewportP* viewport = g.Viewports[n];
14484
25.7k
        viewport->Idx = n;
14485
14486
        // Erase unused viewports
14487
25.7k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14488
0
        {
14489
0
            DestroyViewport(viewport);
14490
0
            n--;
14491
0
            continue;
14492
0
        }
14493
14494
25.7k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14495
25.7k
        if (viewports_enabled)
14496
0
        {
14497
            // Update Position and Size (from Platform Window to ImGui) if requested.
14498
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14499
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14500
0
            {
14501
                // Viewport->WorkPos and WorkSize will be updated below
14502
0
                if (viewport->PlatformRequestMove)
14503
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14504
0
                if (viewport->PlatformRequestResize)
14505
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14506
0
            }
14507
0
        }
14508
14509
        // Update/copy monitor info
14510
25.7k
        UpdateViewportPlatformMonitor(viewport);
14511
14512
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14513
25.7k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14514
25.7k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14515
25.7k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14516
25.7k
        viewport->UpdateWorkRect();
14517
14518
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14519
25.7k
        viewport->Alpha = 1.0f;
14520
14521
        // Translate Dear ImGui windows when a Host Viewport has been moved
14522
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14523
25.7k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14524
25.7k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14525
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14526
14527
        // Update DPI scale
14528
25.7k
        float new_dpi_scale;
14529
25.7k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14530
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14531
25.7k
        else if (viewport->PlatformMonitor != -1)
14532
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14533
25.7k
        else
14534
25.7k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14535
25.7k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14536
0
        {
14537
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14538
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14539
0
                ScaleWindowsInViewport(viewport, scale_factor);
14540
            //if (viewport == GetMainViewport())
14541
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14542
14543
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14544
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14545
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14546
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14547
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
14548
0
        }
14549
25.7k
        viewport->DpiScale = new_dpi_scale;
14550
25.7k
    }
14551
14552
    // Update fallback monitor
14553
25.7k
    if (g.PlatformIO.Monitors.Size == 0)
14554
25.7k
    {
14555
25.7k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14556
25.7k
        monitor->MainPos = main_viewport->Pos;
14557
25.7k
        monitor->MainSize = main_viewport->Size;
14558
25.7k
        monitor->WorkPos = main_viewport->WorkPos;
14559
25.7k
        monitor->WorkSize = main_viewport->WorkSize;
14560
25.7k
        monitor->DpiScale = main_viewport->DpiScale;
14561
25.7k
    }
14562
14563
25.7k
    if (!viewports_enabled)
14564
25.7k
    {
14565
25.7k
        g.MouseViewport = main_viewport;
14566
25.7k
        return;
14567
25.7k
    }
14568
14569
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14570
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14571
0
    ImGuiViewportP* viewport_hovered = NULL;
14572
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14573
0
    {
14574
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14575
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14576
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14577
0
    }
14578
0
    else
14579
0
    {
14580
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14581
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14582
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14583
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14584
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14585
0
    }
14586
0
    if (viewport_hovered != NULL)
14587
0
        g.MouseLastHoveredViewport = viewport_hovered;
14588
0
    else if (g.MouseLastHoveredViewport == NULL)
14589
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14590
14591
    // Update mouse reference viewport
14592
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14593
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14594
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14595
0
        g.MouseViewport = g.MovingWindow->Viewport;
14596
0
    else
14597
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14598
14599
    // When dragging something, always refer to the last hovered viewport.
14600
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14601
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14602
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14603
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14604
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14605
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14606
0
        viewport_hovered = g.MouseLastHoveredViewport;
14607
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14608
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14609
0
            g.MouseViewport = viewport_hovered;
14610
14611
0
    IM_ASSERT(g.MouseViewport != NULL);
14612
0
}
14613
14614
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14615
static void ImGui::UpdateViewportsEndFrame()
14616
25.7k
{
14617
25.7k
    ImGuiContext& g = *GImGui;
14618
25.7k
    g.PlatformIO.Viewports.resize(0);
14619
51.5k
    for (int i = 0; i < g.Viewports.Size; i++)
14620
25.7k
    {
14621
25.7k
        ImGuiViewportP* viewport = g.Viewports[i];
14622
25.7k
        viewport->LastPos = viewport->Pos;
14623
25.7k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14624
0
            if (i > 0) // Always include main viewport in the list
14625
0
                continue;
14626
25.7k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14627
0
            continue;
14628
25.7k
        if (i > 0)
14629
25.7k
            IM_ASSERT(viewport->Window != NULL);
14630
25.7k
        g.PlatformIO.Viewports.push_back(viewport);
14631
25.7k
    }
14632
25.7k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14633
25.7k
}
14634
14635
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14636
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14637
25.7k
{
14638
25.7k
    ImGuiContext& g = *GImGui;
14639
25.7k
    IM_ASSERT(id != 0);
14640
14641
25.7k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14642
25.7k
    if (window != NULL)
14643
0
    {
14644
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14645
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14646
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14647
0
            flags |= ImGuiViewportFlags_NoInputs;
14648
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14649
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14650
0
    }
14651
14652
25.7k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14653
25.7k
    if (viewport)
14654
25.7k
    {
14655
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14656
25.7k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14657
25.7k
            viewport->Pos = pos;
14658
25.7k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14659
25.7k
            viewport->Size = size;
14660
25.7k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14661
25.7k
    }
14662
0
    else
14663
0
    {
14664
        // New viewport
14665
0
        viewport = IM_NEW(ImGuiViewportP)();
14666
0
        viewport->ID = id;
14667
0
        viewport->Idx = g.Viewports.Size;
14668
0
        viewport->Pos = viewport->LastPos = pos;
14669
0
        viewport->Size = size;
14670
0
        viewport->Flags = flags;
14671
0
        UpdateViewportPlatformMonitor(viewport);
14672
0
        g.Viewports.push_back(viewport);
14673
0
        g.ViewportCreatedCount++;
14674
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14675
14676
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14677
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14678
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14679
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14680
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14681
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14682
14683
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14684
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14685
0
        if (viewport->PlatformMonitor != -1)
14686
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14687
0
    }
14688
14689
25.7k
    viewport->Window = window;
14690
25.7k
    viewport->LastFrameActive = g.FrameCount;
14691
25.7k
    viewport->UpdateWorkRect();
14692
25.7k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14693
14694
25.7k
    if (window != NULL)
14695
0
        window->ViewportOwned = true;
14696
14697
25.7k
    return viewport;
14698
25.7k
}
14699
14700
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14701
0
{
14702
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14703
0
    ImGuiContext& g = *GImGui;
14704
0
    for (ImGuiWindow* window : g.Windows)
14705
0
    {
14706
0
        if (window->Viewport != viewport)
14707
0
            continue;
14708
0
        window->Viewport = NULL;
14709
0
        window->ViewportOwned = false;
14710
0
    }
14711
0
    if (viewport == g.MouseLastHoveredViewport)
14712
0
        g.MouseLastHoveredViewport = NULL;
14713
14714
    // Destroy
14715
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14716
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14717
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14718
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14719
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14720
0
    IM_DELETE(viewport);
14721
0
}
14722
14723
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14724
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14725
77.3k
{
14726
77.3k
    ImGuiContext& g = *GImGui;
14727
77.3k
    ImGuiWindowFlags flags = window->Flags;
14728
77.3k
    window->ViewportAllowPlatformMonitorExtend = -1;
14729
14730
    // Restore main viewport if multi-viewport is not supported by the backend
14731
77.3k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14732
77.3k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14733
77.3k
    {
14734
77.3k
        SetWindowViewport(window, main_viewport);
14735
77.3k
        return;
14736
77.3k
    }
14737
0
    window->ViewportOwned = false;
14738
14739
    // Appearing popups reset their viewport so they can inherit again
14740
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14741
0
    {
14742
0
        window->Viewport = NULL;
14743
0
        window->ViewportId = 0;
14744
0
    }
14745
14746
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14747
0
    {
14748
        // By default inherit from parent window
14749
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14750
0
            window->Viewport = window->ParentWindow->Viewport;
14751
14752
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14753
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14754
0
        {
14755
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14756
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14757
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14758
0
        }
14759
0
    }
14760
14761
0
    bool lock_viewport = false;
14762
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14763
0
    {
14764
        // Code explicitly request a viewport
14765
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14766
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14767
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
14768
0
        {
14769
0
            window->Viewport->Window = window;
14770
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
14771
0
        }
14772
0
        lock_viewport = true;
14773
0
    }
14774
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14775
0
    {
14776
        // Always inherit viewport from parent window
14777
0
        if (window->DockNode && window->DockNode->HostWindow)
14778
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14779
0
        window->Viewport = window->ParentWindow->Viewport;
14780
0
    }
14781
0
    else if (window->DockNode && window->DockNode->HostWindow)
14782
0
    {
14783
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14784
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14785
0
    }
14786
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14787
0
    {
14788
0
        window->Viewport = g.MouseViewport;
14789
0
    }
14790
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14791
0
    {
14792
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14793
0
    }
14794
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14795
0
    {
14796
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14797
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14798
0
    }
14799
0
    else
14800
0
    {
14801
        // Merge into host viewport?
14802
        // We cannot test window->ViewportOwned as it set lower in the function.
14803
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14804
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14805
0
        if (try_to_merge_into_host_viewport)
14806
0
            UpdateTryMergeWindowIntoHostViewports(window);
14807
0
    }
14808
14809
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14810
0
    if (window->Viewport == NULL)
14811
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14812
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14813
14814
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14815
0
    if (!lock_viewport)
14816
0
    {
14817
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14818
0
        {
14819
            // We need to take account of the possibility that mouse may become invalid.
14820
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14821
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14822
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14823
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14824
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14825
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14826
0
            else
14827
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14828
0
        }
14829
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14830
0
        {
14831
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14832
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14833
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14834
0
            {
14835
                // Steal/transfer ownership
14836
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14837
0
                window->Viewport->Window = window;
14838
0
                window->Viewport->ID = window->ID;
14839
0
                window->Viewport->LastNameHash = 0;
14840
0
            }
14841
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14842
0
            {
14843
                // New viewport
14844
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14845
0
            }
14846
0
        }
14847
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14848
0
        {
14849
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14850
            // Child windows are kept contained within their parent.
14851
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14852
0
        }
14853
0
    }
14854
14855
    // Update flags
14856
0
    window->ViewportOwned = (window == window->Viewport->Window);
14857
0
    window->ViewportId = window->Viewport->ID;
14858
14859
    // If the OS window has a title bar, hide our imgui title bar
14860
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14861
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14862
0
}
14863
14864
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14865
0
{
14866
0
    ImGuiContext& g = *GImGui;
14867
14868
0
    bool viewport_rect_changed = false;
14869
14870
    // Synchronize window --> viewport in most situations
14871
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14872
0
    if (window->Viewport->PlatformRequestMove)
14873
0
    {
14874
0
        window->Pos = window->Viewport->Pos;
14875
0
        MarkIniSettingsDirty(window);
14876
0
    }
14877
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14878
0
    {
14879
0
        viewport_rect_changed = true;
14880
0
        window->Viewport->Pos = window->Pos;
14881
0
    }
14882
14883
0
    if (window->Viewport->PlatformRequestResize)
14884
0
    {
14885
0
        window->Size = window->SizeFull = window->Viewport->Size;
14886
0
        MarkIniSettingsDirty(window);
14887
0
    }
14888
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14889
0
    {
14890
0
        viewport_rect_changed = true;
14891
0
        window->Viewport->Size = window->Size;
14892
0
    }
14893
0
    window->Viewport->UpdateWorkRect();
14894
14895
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14896
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14897
0
    if (viewport_rect_changed)
14898
0
        UpdateViewportPlatformMonitor(window->Viewport);
14899
14900
    // Update common viewport flags
14901
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14902
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14903
0
    ImGuiWindowFlags window_flags = window->Flags;
14904
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14905
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14906
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14907
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14908
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14909
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14910
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14911
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14912
14913
    // Not correct to set modal as topmost because:
14914
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14915
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14916
    //if (flags & ImGuiWindowFlags_Modal)
14917
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14918
14919
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14920
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14921
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14922
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14923
0
    if (is_short_lived_floating_window && !is_modal)
14924
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14925
14926
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14927
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14928
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14929
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14930
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14931
14932
    // We can also tell the backend that clearing the platform window won't be necessary,
14933
    // as our window background is filling the viewport and we have disabled BgAlpha.
14934
    // FIXME: Work on support for per-viewport transparency (#2766)
14935
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14936
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14937
14938
0
    window->Viewport->Flags = viewport_flags;
14939
14940
    // Update parent viewport ID
14941
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14942
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14943
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14944
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14945
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14946
0
    else
14947
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14948
0
}
14949
14950
// Called by user at the end of the main loop, after EndFrame()
14951
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14952
void ImGui::UpdatePlatformWindows()
14953
0
{
14954
0
    ImGuiContext& g = *GImGui;
14955
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14956
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14957
0
    g.FrameCountPlatformEnded = g.FrameCount;
14958
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14959
0
        return;
14960
14961
    // Create/resize/destroy platform windows to match each active viewport.
14962
    // Skip the main viewport (index 0), which is always fully handled by the application!
14963
0
    for (int i = 1; i < g.Viewports.Size; i++)
14964
0
    {
14965
0
        ImGuiViewportP* viewport = g.Viewports[i];
14966
14967
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14968
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14969
0
        bool destroy_platform_window = false;
14970
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14971
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14972
0
        if (destroy_platform_window)
14973
0
        {
14974
0
            DestroyPlatformWindow(viewport);
14975
0
            continue;
14976
0
        }
14977
14978
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14979
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14980
0
            continue;
14981
14982
        // Create window
14983
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14984
0
        if (is_new_platform_window)
14985
0
        {
14986
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14987
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14988
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14989
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14990
0
            g.PlatformWindowsCreatedCount++;
14991
0
            viewport->LastNameHash = 0;
14992
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14993
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14994
0
            viewport->PlatformWindowCreated = true;
14995
0
        }
14996
14997
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14998
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14999
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15000
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15001
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15002
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15003
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15004
0
        viewport->LastPlatformPos = viewport->Pos;
15005
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15006
15007
        // Update title bar (if it changed)
15008
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15009
0
        {
15010
0
            const char* title_begin = window_for_title->Name;
15011
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15012
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15013
0
            if (viewport->LastNameHash != title_hash)
15014
0
            {
15015
0
                char title_end_backup_c = *title_end;
15016
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15017
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15018
0
                *title_end = title_end_backup_c;
15019
0
                viewport->LastNameHash = title_hash;
15020
0
            }
15021
0
        }
15022
15023
        // Update alpha (if it changed)
15024
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15025
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15026
0
        viewport->LastAlpha = viewport->Alpha;
15027
15028
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15029
0
        if (g.PlatformIO.Platform_UpdateWindow)
15030
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15031
15032
0
        if (is_new_platform_window)
15033
0
        {
15034
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15035
0
            if (g.FrameCount < 3)
15036
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15037
15038
            // Show window
15039
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15040
15041
            // Even without focus, we assume the window becomes front-most.
15042
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15043
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15044
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15045
0
        }
15046
15047
        // Clear request flags
15048
0
        viewport->ClearRequestFlags();
15049
0
    }
15050
0
}
15051
15052
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15053
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15054
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15055
//
15056
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15057
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15058
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15059
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15060
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15061
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15062
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15063
//
15064
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15065
0
{
15066
    // Skip the main viewport (index 0), which is always fully handled by the application!
15067
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15068
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15069
0
    {
15070
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15071
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15072
0
            continue;
15073
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15074
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15075
0
    }
15076
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15077
0
    {
15078
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15079
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15080
0
            continue;
15081
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15082
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15083
0
    }
15084
0
}
15085
15086
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15087
0
{
15088
0
    ImGuiContext& g = *GImGui;
15089
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15090
0
    {
15091
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15092
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15093
0
            return monitor_n;
15094
0
    }
15095
0
    return -1;
15096
0
}
15097
15098
// Search for the monitor with the largest intersection area with the given rectangle
15099
// We generally try to avoid searching loops but the monitor count should be very small here
15100
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15101
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15102
25.7k
{
15103
25.7k
    ImGuiContext& g = *GImGui;
15104
15105
25.7k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15106
25.7k
    if (monitor_count <= 1)
15107
25.7k
        return monitor_count - 1;
15108
15109
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15110
    // This is necessary for tooltips which always resize down to zero at first.
15111
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15112
0
    int best_monitor_n = -1;
15113
0
    float best_monitor_surface = 0.001f;
15114
15115
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15116
0
    {
15117
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15118
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15119
0
        if (monitor_rect.Contains(rect))
15120
0
            return monitor_n;
15121
0
        ImRect overlapping_rect = rect;
15122
0
        overlapping_rect.ClipWithFull(monitor_rect);
15123
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15124
0
        if (overlapping_surface < best_monitor_surface)
15125
0
            continue;
15126
0
        best_monitor_surface = overlapping_surface;
15127
0
        best_monitor_n = monitor_n;
15128
0
    }
15129
0
    return best_monitor_n;
15130
0
}
15131
15132
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15133
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15134
25.7k
{
15135
25.7k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15136
25.7k
}
15137
15138
// Return value is always != NULL, but don't hold on it across frames.
15139
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15140
0
{
15141
0
    ImGuiContext& g = *GImGui;
15142
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15143
0
    int monitor_idx = viewport->PlatformMonitor;
15144
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15145
0
        return &g.PlatformIO.Monitors[monitor_idx];
15146
0
    return &g.FallbackMonitor;
15147
0
}
15148
15149
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15150
0
{
15151
0
    ImGuiContext& g = *GImGui;
15152
0
    if (viewport->PlatformWindowCreated)
15153
0
    {
15154
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15155
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15156
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15157
0
        if (g.PlatformIO.Platform_DestroyWindow)
15158
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15159
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15160
15161
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15162
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15163
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15164
0
            viewport->PlatformWindowCreated = false;
15165
0
    }
15166
0
    else
15167
0
    {
15168
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15169
0
    }
15170
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15171
0
    viewport->ClearRequestFlags();
15172
0
}
15173
15174
void ImGui::DestroyPlatformWindows()
15175
0
{
15176
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15177
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15178
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15179
    // code to operator a consistent manner.
15180
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15181
    // crashing if it doesn't have data stored.
15182
0
    ImGuiContext& g = *GImGui;
15183
0
    for (ImGuiViewportP* viewport : g.Viewports)
15184
0
        DestroyPlatformWindow(viewport);
15185
0
}
15186
15187
15188
//-----------------------------------------------------------------------------
15189
// [SECTION] DOCKING
15190
//-----------------------------------------------------------------------------
15191
// Docking: Internal Types
15192
// Docking: Forward Declarations
15193
// Docking: ImGuiDockContext
15194
// Docking: ImGuiDockContext Docking/Undocking functions
15195
// Docking: ImGuiDockNode
15196
// Docking: ImGuiDockNode Tree manipulation functions
15197
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15198
// Docking: Builder Functions
15199
// Docking: Begin/End Support Functions (called from Begin/End)
15200
// Docking: Settings
15201
//-----------------------------------------------------------------------------
15202
15203
//-----------------------------------------------------------------------------
15204
// Typical Docking call flow: (root level is generally public API):
15205
//-----------------------------------------------------------------------------
15206
// - NewFrame()                               new dear imgui frame
15207
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15208
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15209
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15210
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15211
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15212
//    | - DockContextProcessDock()            - process one docking request
15213
//    | - DockNodeUpdate()
15214
//    |   - DockNodeUpdateForRootNode()
15215
//    |     - DockNodeUpdateFlagsAndCollapse()
15216
//    |     - DockNodeFindInfo()
15217
//    |   - destroy unused node or tab bar
15218
//    |   - create dock node host window
15219
//    |      - Begin() etc.
15220
//    |   - DockNodeStartMouseMovingWindow()
15221
//    |   - DockNodeTreeUpdatePosSize()
15222
//    |   - DockNodeTreeUpdateSplitter()
15223
//    |   - draw node background
15224
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15225
//    |     - DockNodeAddTabBar()
15226
//    |     - DockNodeWindowMenuUpdate()
15227
//    |     - DockNodeCalcTabBarLayout()
15228
//    |     - BeginTabBarEx()
15229
//    |     - TabItemEx() calls
15230
//    |     - EndTabBar()
15231
//    |   - BeginDockableDragDropTarget()
15232
//    |      - DockNodeUpdate()               - recurse into child nodes...
15233
//-----------------------------------------------------------------------------
15234
// - DockSpace()                              user submit a dockspace into a window
15235
//    | Begin(Child)                          - create a child window
15236
//    | DockNodeUpdate()                      - call main dock node update function
15237
//    | End(Child)
15238
//    | ItemSize()
15239
//-----------------------------------------------------------------------------
15240
// - Begin()
15241
//    | BeginDocked()
15242
//    | BeginDockableDragDropSource()
15243
//    | BeginDockableDragDropTarget()
15244
//    | - DockNodePreviewDockRender()
15245
//-----------------------------------------------------------------------------
15246
// - EndFrame()
15247
//    | DockContextEndFrame()
15248
//-----------------------------------------------------------------------------
15249
15250
//-----------------------------------------------------------------------------
15251
// Docking: Internal Types
15252
//-----------------------------------------------------------------------------
15253
// - ImGuiDockRequestType
15254
// - ImGuiDockRequest
15255
// - ImGuiDockPreviewData
15256
// - ImGuiDockNodeSettings
15257
// - ImGuiDockContext
15258
//-----------------------------------------------------------------------------
15259
15260
enum ImGuiDockRequestType
15261
{
15262
    ImGuiDockRequestType_None = 0,
15263
    ImGuiDockRequestType_Dock,
15264
    ImGuiDockRequestType_Undock,
15265
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15266
};
15267
15268
struct ImGuiDockRequest
15269
{
15270
    ImGuiDockRequestType    Type;
15271
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15272
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15273
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15274
    ImGuiDir                DockSplitDir;
15275
    float                   DockSplitRatio;
15276
    bool                    DockSplitOuter;
15277
    ImGuiWindow*            UndockTargetWindow;
15278
    ImGuiDockNode*          UndockTargetNode;
15279
15280
    ImGuiDockRequest()
15281
0
    {
15282
0
        Type = ImGuiDockRequestType_None;
15283
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15284
0
        DockTargetNode = UndockTargetNode = NULL;
15285
0
        DockSplitDir = ImGuiDir_None;
15286
0
        DockSplitRatio = 0.5f;
15287
0
        DockSplitOuter = false;
15288
0
    }
15289
};
15290
15291
struct ImGuiDockPreviewData
15292
{
15293
    ImGuiDockNode   FutureNode;
15294
    bool            IsDropAllowed;
15295
    bool            IsCenterAvailable;
15296
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15297
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15298
    ImGuiDockNode*  SplitNode;
15299
    ImGuiDir        SplitDir;
15300
    float           SplitRatio;
15301
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15302
15303
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15304
};
15305
15306
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15307
struct ImGuiDockNodeSettings
15308
{
15309
    ImGuiID             ID;
15310
    ImGuiID             ParentNodeId;
15311
    ImGuiID             ParentWindowId;
15312
    ImGuiID             SelectedTabId;
15313
    signed char         SplitAxis;
15314
    char                Depth;
15315
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15316
    ImVec2ih            Pos;
15317
    ImVec2ih            Size;
15318
    ImVec2ih            SizeRef;
15319
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15320
};
15321
15322
//-----------------------------------------------------------------------------
15323
// Docking: Forward Declarations
15324
//-----------------------------------------------------------------------------
15325
15326
namespace ImGui
15327
{
15328
    // ImGuiDockContext
15329
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15330
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15331
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15332
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15333
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15334
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15335
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15336
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
15337
15338
    // ImGuiDockNode
15339
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15340
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15341
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15342
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15343
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15344
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15345
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
15346
    static void             DockNodeUpdate(ImGuiDockNode* node);
15347
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
15348
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15349
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15350
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15351
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
15352
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
15353
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15354
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15355
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15356
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15357
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15358
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15359
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15360
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15361
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15362
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15363
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
15364
15365
    // ImGuiDockNode tree manipulations
15366
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15367
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15368
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15369
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15370
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15371
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15372
15373
    // Settings
15374
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15375
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15376
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15377
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15378
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15379
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15380
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15381
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15382
}
15383
15384
//-----------------------------------------------------------------------------
15385
// Docking: ImGuiDockContext
15386
//-----------------------------------------------------------------------------
15387
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15388
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15389
// At boot time only, we run a simple GC to remove nodes that have no references.
15390
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15391
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15392
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15393
//-----------------------------------------------------------------------------
15394
// - DockContextInitialize()
15395
// - DockContextShutdown()
15396
// - DockContextClearNodes()
15397
// - DockContextRebuildNodes()
15398
// - DockContextNewFrameUpdateUndocking()
15399
// - DockContextNewFrameUpdateDocking()
15400
// - DockContextEndFrame()
15401
// - DockContextFindNodeByID()
15402
// - DockContextBindNodeToWindow()
15403
// - DockContextGenNodeID()
15404
// - DockContextAddNode()
15405
// - DockContextRemoveNode()
15406
// - ImGuiDockContextPruneNodeData
15407
// - DockContextPruneUnusedSettingsNodes()
15408
// - DockContextBuildNodesFromSettings()
15409
// - DockContextBuildAddWindowsToNodes()
15410
//-----------------------------------------------------------------------------
15411
15412
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15413
1
{
15414
1
    ImGuiContext& g = *ctx;
15415
15416
    // Add .ini handle for persistent docking data
15417
1
    ImGuiSettingsHandler ini_handler;
15418
1
    ini_handler.TypeName = "Docking";
15419
1
    ini_handler.TypeHash = ImHashStr("Docking");
15420
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15421
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15422
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15423
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15424
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15425
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15426
1
    g.SettingsHandlers.push_back(ini_handler);
15427
15428
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15429
1
}
15430
15431
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15432
0
{
15433
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15434
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15435
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15436
0
            IM_DELETE(node);
15437
0
}
15438
15439
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15440
0
{
15441
0
    IM_UNUSED(ctx);
15442
0
    IM_ASSERT(ctx == GImGui);
15443
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15444
0
    DockBuilderRemoveNodeChildNodes(root_id);
15445
0
}
15446
15447
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15448
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15449
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15450
0
{
15451
0
    ImGuiContext& g = *ctx;
15452
0
    ImGuiDockContext* dc = &ctx->DockContext;
15453
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15454
0
    SaveIniSettingsToMemory();
15455
0
    ImGuiID root_id = 0; // Rebuild all
15456
0
    DockContextClearNodes(ctx, root_id, false);
15457
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15458
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15459
0
}
15460
15461
// Docking context update function, called by NewFrame()
15462
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15463
25.7k
{
15464
25.7k
    ImGuiContext& g = *ctx;
15465
25.7k
    ImGuiDockContext* dc = &ctx->DockContext;
15466
25.7k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15467
0
    {
15468
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15469
0
            DockContextClearNodes(ctx, 0, true);
15470
0
        return;
15471
0
    }
15472
15473
    // Setting NoSplit at runtime merges all nodes
15474
25.7k
    if (g.IO.ConfigDockingNoSplit)
15475
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15476
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15477
0
                if (node->IsRootNode() && node->IsSplitNode())
15478
0
                {
15479
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15480
                    //dc->WantFullRebuild = true;
15481
0
                }
15482
15483
    // Process full rebuild
15484
#if 0
15485
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15486
        dc->WantFullRebuild = true;
15487
#endif
15488
25.7k
    if (dc->WantFullRebuild)
15489
0
    {
15490
0
        DockContextRebuildNodes(ctx);
15491
0
        dc->WantFullRebuild = false;
15492
0
    }
15493
15494
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15495
25.7k
    for (ImGuiDockRequest& req : dc->Requests)
15496
0
    {
15497
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
15498
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
15499
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
15500
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
15501
0
    }
15502
25.7k
}
15503
15504
// Docking context update function, called by NewFrame()
15505
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15506
25.7k
{
15507
25.7k
    ImGuiContext& g = *ctx;
15508
25.7k
    ImGuiDockContext* dc  = &ctx->DockContext;
15509
25.7k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15510
0
        return;
15511
15512
    // [DEBUG] Store hovered dock node.
15513
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15514
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15515
25.7k
    g.DebugHoveredDockNode = NULL;
15516
25.7k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15517
2.30k
    {
15518
2.30k
        if (hovered_window->DockNodeAsHost)
15519
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15520
2.30k
        else if (hovered_window->RootWindow->DockNode)
15521
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15522
2.30k
    }
15523
15524
    // Process Docking requests
15525
25.7k
    for (ImGuiDockRequest& req : dc->Requests)
15526
0
        if (req.Type == ImGuiDockRequestType_Dock)
15527
0
            DockContextProcessDock(ctx, &req);
15528
25.7k
    dc->Requests.resize(0);
15529
15530
    // Create windows for each automatic docking nodes
15531
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15532
25.7k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15533
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15534
0
            if (node->IsFloatingNode())
15535
0
                DockNodeUpdate(node);
15536
25.7k
}
15537
15538
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15539
25.7k
{
15540
    // Draw backgrounds of node missing their window
15541
25.7k
    ImGuiContext& g = *ctx;
15542
25.7k
    ImGuiDockContext* dc = &g.DockContext;
15543
25.7k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15544
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15545
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15546
0
            {
15547
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15548
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
15549
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15550
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15551
0
            }
15552
25.7k
}
15553
15554
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15555
0
{
15556
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15557
0
}
15558
15559
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15560
0
{
15561
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15562
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15563
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15564
0
    ImGuiID id = 0x0001;
15565
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15566
0
        id++;
15567
0
    return id;
15568
0
}
15569
15570
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15571
0
{
15572
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15573
0
    ImGuiContext& g = *ctx;
15574
0
    if (id == 0)
15575
0
        id = DockContextGenNodeID(ctx);
15576
0
    else
15577
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15578
15579
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15580
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15581
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15582
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15583
0
    return node;
15584
0
}
15585
15586
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15587
0
{
15588
0
    ImGuiContext& g = *ctx;
15589
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15590
15591
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15592
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15593
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15594
0
    IM_ASSERT(node->Windows.Size == 0);
15595
15596
0
    if (node->HostWindow)
15597
0
        node->HostWindow->DockNodeAsHost = NULL;
15598
15599
0
    ImGuiDockNode* parent_node = node->ParentNode;
15600
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15601
0
    if (merge)
15602
0
    {
15603
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15604
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15605
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15606
0
    }
15607
0
    else
15608
0
    {
15609
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15610
0
            if (parent_node->ChildNodes[n] == node)
15611
0
                node->ParentNode->ChildNodes[n] = NULL;
15612
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15613
0
        IM_DELETE(node);
15614
0
    }
15615
0
}
15616
15617
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15618
0
{
15619
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15620
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15621
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15622
0
}
15623
15624
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15625
struct ImGuiDockContextPruneNodeData
15626
{
15627
    int         CountWindows, CountChildWindows, CountChildNodes;
15628
    ImGuiID     RootId;
15629
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15630
};
15631
15632
// Garbage collect unused nodes (run once at init time)
15633
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15634
0
{
15635
0
    ImGuiContext& g = *ctx;
15636
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15637
0
    IM_ASSERT(g.Windows.Size == 0);
15638
15639
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15640
0
    pool.Reserve(dc->NodesSettings.Size);
15641
15642
    // Count child nodes and compute RootID
15643
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15644
0
    {
15645
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15646
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15647
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15648
0
        if (settings->ParentNodeId)
15649
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15650
0
    }
15651
15652
    // Count reference to dock ids from dockspaces
15653
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15654
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15655
0
    {
15656
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15657
0
        if (settings->ParentWindowId != 0)
15658
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15659
0
                if (window_settings->DockId)
15660
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15661
0
                        data->CountChildNodes++;
15662
0
    }
15663
15664
    // Count reference to dock ids from window settings
15665
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15666
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15667
0
        if (ImGuiID dock_id = settings->DockId)
15668
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15669
0
            {
15670
0
                data->CountWindows++;
15671
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15672
0
                    data_root->CountChildWindows++;
15673
0
            }
15674
15675
    // Prune
15676
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15677
0
    {
15678
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15679
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15680
0
        if (data->CountWindows > 1)
15681
0
            continue;
15682
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15683
15684
0
        bool remove = false;
15685
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15686
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15687
0
        remove |= (data_root->CountChildWindows == 0);
15688
0
        if (remove)
15689
0
        {
15690
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15691
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15692
0
            settings->ID = 0;
15693
0
        }
15694
0
    }
15695
0
}
15696
15697
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15698
0
{
15699
    // Build nodes
15700
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15701
0
    {
15702
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15703
0
        if (settings->ID == 0)
15704
0
            continue;
15705
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15706
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15707
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15708
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15709
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15710
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15711
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15712
0
            node->ParentNode->ChildNodes[0] = node;
15713
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15714
0
            node->ParentNode->ChildNodes[1] = node;
15715
0
        node->SelectedTabId = settings->SelectedTabId;
15716
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15717
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15718
15719
        // Bind host window immediately if it already exist (in case of a rebuild)
15720
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15721
0
        char host_window_title[20];
15722
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15723
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15724
0
    }
15725
0
}
15726
15727
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15728
0
{
15729
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15730
0
    ImGuiContext& g = *ctx;
15731
0
    for (ImGuiWindow* window : g.Windows)
15732
0
    {
15733
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15734
0
            continue;
15735
0
        if (window->DockNode != NULL)
15736
0
            continue;
15737
15738
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15739
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15740
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15741
0
            DockNodeAddWindow(node, window, true);
15742
0
    }
15743
0
}
15744
15745
//-----------------------------------------------------------------------------
15746
// Docking: ImGuiDockContext Docking/Undocking functions
15747
//-----------------------------------------------------------------------------
15748
// - DockContextQueueDock()
15749
// - DockContextQueueUndockWindow()
15750
// - DockContextQueueUndockNode()
15751
// - DockContextQueueNotifyRemovedNode()
15752
// - DockContextProcessDock()
15753
// - DockContextProcessUndockWindow()
15754
// - DockContextProcessUndockNode()
15755
// - DockContextCalcDropPosForDocking()
15756
//-----------------------------------------------------------------------------
15757
15758
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15759
0
{
15760
0
    IM_ASSERT(target != payload);
15761
0
    ImGuiDockRequest req;
15762
0
    req.Type = ImGuiDockRequestType_Dock;
15763
0
    req.DockTargetWindow = target;
15764
0
    req.DockTargetNode = target_node;
15765
0
    req.DockPayload = payload;
15766
0
    req.DockSplitDir = split_dir;
15767
0
    req.DockSplitRatio = split_ratio;
15768
0
    req.DockSplitOuter = split_outer;
15769
0
    ctx->DockContext.Requests.push_back(req);
15770
0
}
15771
15772
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15773
0
{
15774
0
    ImGuiDockRequest req;
15775
0
    req.Type = ImGuiDockRequestType_Undock;
15776
0
    req.UndockTargetWindow = window;
15777
0
    ctx->DockContext.Requests.push_back(req);
15778
0
}
15779
15780
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15781
0
{
15782
0
    ImGuiDockRequest req;
15783
0
    req.Type = ImGuiDockRequestType_Undock;
15784
0
    req.UndockTargetNode = node;
15785
0
    ctx->DockContext.Requests.push_back(req);
15786
0
}
15787
15788
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15789
0
{
15790
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15791
0
    for (ImGuiDockRequest& req : dc->Requests)
15792
0
        if (req.DockTargetNode == node)
15793
0
            req.Type = ImGuiDockRequestType_None;
15794
0
}
15795
15796
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15797
0
{
15798
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15799
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15800
15801
0
    ImGuiContext& g = *ctx;
15802
0
    IM_UNUSED(g);
15803
15804
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15805
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15806
0
    ImGuiDockNode* node = req->DockTargetNode;
15807
0
    if (payload_window)
15808
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15809
0
    else
15810
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15811
15812
    // Decide which Tab will be selected at the end of the operation
15813
0
    ImGuiID next_selected_id = 0;
15814
0
    ImGuiDockNode* payload_node = NULL;
15815
0
    if (payload_window)
15816
0
    {
15817
0
        payload_node = payload_window->DockNodeAsHost;
15818
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15819
0
        if (payload_node && payload_node->IsLeafNode())
15820
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15821
0
        if (payload_node == NULL)
15822
0
            next_selected_id = payload_window->TabId;
15823
0
    }
15824
15825
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15826
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15827
0
    if (node)
15828
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15829
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15830
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15831
15832
    // Create new node and add existing window to it
15833
0
    if (node == NULL)
15834
0
    {
15835
0
        node = DockContextAddNode(ctx, 0);
15836
0
        node->Pos = target_window->Pos;
15837
0
        node->Size = target_window->Size;
15838
0
        if (target_window->DockNodeAsHost == NULL)
15839
0
        {
15840
0
            DockNodeAddWindow(node, target_window, true);
15841
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15842
0
            target_window->DockIsActive = true;
15843
0
        }
15844
0
    }
15845
15846
0
    ImGuiDir split_dir = req->DockSplitDir;
15847
0
    if (split_dir != ImGuiDir_None)
15848
0
    {
15849
        // Split into two, one side will be our payload node unless we are dropping a loose window
15850
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15851
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15852
0
        const float split_ratio = req->DockSplitRatio;
15853
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15854
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15855
0
        new_node->HostWindow = node->HostWindow;
15856
0
        node = new_node;
15857
0
    }
15858
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15859
15860
0
    if (node != payload_node)
15861
0
    {
15862
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15863
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15864
0
        {
15865
0
            DockNodeAddTabBar(node);
15866
0
            for (int n = 0; n < node->Windows.Size; n++)
15867
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15868
0
        }
15869
15870
0
        if (payload_node != NULL)
15871
0
        {
15872
            // Transfer full payload node (with 1+ child windows or child nodes)
15873
0
            if (payload_node->IsSplitNode())
15874
0
            {
15875
0
                if (node->Windows.Size > 0)
15876
0
                {
15877
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15878
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15879
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15880
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15881
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15882
0
                    if (visible_node->TabBar)
15883
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15884
0
                    DockNodeMoveWindows(node, visible_node);
15885
0
                    DockNodeMoveWindows(visible_node, node);
15886
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15887
0
                }
15888
0
                if (node->IsCentralNode())
15889
0
                {
15890
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15891
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15892
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15893
0
                    IM_ASSERT(last_focused_node != NULL);
15894
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15895
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15896
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15897
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15898
0
                    last_focused_root_node->CentralNode = last_focused_node;
15899
0
                }
15900
15901
0
                IM_ASSERT(node->Windows.Size == 0);
15902
0
                DockNodeMoveChildNodes(node, payload_node);
15903
0
            }
15904
0
            else
15905
0
            {
15906
0
                const ImGuiID payload_dock_id = payload_node->ID;
15907
0
                DockNodeMoveWindows(node, payload_node);
15908
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15909
0
            }
15910
0
            DockContextRemoveNode(ctx, payload_node, true);
15911
0
        }
15912
0
        else if (payload_window)
15913
0
        {
15914
            // Transfer single window
15915
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15916
0
            node->VisibleWindow = payload_window;
15917
0
            DockNodeAddWindow(node, payload_window, true);
15918
0
            if (payload_dock_id != 0)
15919
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15920
0
        }
15921
0
    }
15922
0
    else
15923
0
    {
15924
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15925
0
        node->WantHiddenTabBarUpdate = true;
15926
0
    }
15927
15928
    // Update selection immediately
15929
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15930
0
        tab_bar->NextSelectedTabId = next_selected_id;
15931
0
    MarkIniSettingsDirty();
15932
0
}
15933
15934
// Problem:
15935
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15936
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15937
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15938
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15939
// Solution:
15940
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15941
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15942
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15943
0
{
15944
0
    if (ref_viewport == NULL)
15945
0
        return size;
15946
15947
0
    ImGuiContext& g = *GImGui;
15948
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
15949
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15950
0
    {
15951
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15952
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
15953
0
    }
15954
0
    return ImMin(size, max_size);
15955
0
}
15956
15957
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15958
0
{
15959
0
    ImGuiContext& g = *ctx;
15960
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15961
0
    if (window->DockNode)
15962
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15963
0
    else
15964
0
        window->DockId = 0;
15965
0
    window->Collapsed = false;
15966
0
    window->DockIsActive = false;
15967
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15968
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15969
15970
0
    MarkIniSettingsDirty();
15971
0
}
15972
15973
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15974
0
{
15975
0
    ImGuiContext& g = *ctx;
15976
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15977
0
    IM_ASSERT(node->IsLeafNode());
15978
0
    IM_ASSERT(node->Windows.Size >= 1);
15979
15980
0
    if (node->IsRootNode() || node->IsCentralNode())
15981
0
    {
15982
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15983
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15984
0
        new_node->Pos = node->Pos;
15985
0
        new_node->Size = node->Size;
15986
0
        new_node->SizeRef = node->SizeRef;
15987
0
        DockNodeMoveWindows(new_node, node);
15988
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15989
0
        node = new_node;
15990
0
    }
15991
0
    else
15992
0
    {
15993
        // Otherwise extract our node and merge our sibling back into the parent node.
15994
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15995
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15996
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15997
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15998
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15999
0
        node->ParentNode = NULL;
16000
0
    }
16001
0
    for (ImGuiWindow* window : node->Windows)
16002
0
    {
16003
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16004
0
        if (window->ParentWindow)
16005
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16006
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16007
0
    }
16008
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16009
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16010
0
    node->WantMouseMove = true;
16011
0
    MarkIniSettingsDirty();
16012
0
}
16013
16014
// This is mostly used for automation.
16015
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16016
0
{
16017
0
    if (target != NULL && target_node == NULL)
16018
0
        target_node = target->DockNode;
16019
16020
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16021
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16022
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16023
0
        split_outer = true;
16024
0
    ImGuiDockPreviewData split_data;
16025
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16026
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16027
0
        return false;
16028
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16029
0
    return true;
16030
0
}
16031
16032
//-----------------------------------------------------------------------------
16033
// Docking: ImGuiDockNode
16034
//-----------------------------------------------------------------------------
16035
// - DockNodeGetTabOrder()
16036
// - DockNodeAddWindow()
16037
// - DockNodeRemoveWindow()
16038
// - DockNodeMoveChildNodes()
16039
// - DockNodeMoveWindows()
16040
// - DockNodeApplyPosSizeToWindows()
16041
// - DockNodeHideHostWindow()
16042
// - ImGuiDockNodeFindInfoResults
16043
// - DockNodeFindInfo()
16044
// - DockNodeFindWindowByID()
16045
// - DockNodeUpdateFlagsAndCollapse()
16046
// - DockNodeUpdateHasCentralNodeFlag()
16047
// - DockNodeUpdateVisibleFlag()
16048
// - DockNodeStartMouseMovingWindow()
16049
// - DockNodeUpdate()
16050
// - DockNodeUpdateWindowMenu()
16051
// - DockNodeBeginAmendTabBar()
16052
// - DockNodeEndAmendTabBar()
16053
// - DockNodeUpdateTabBar()
16054
// - DockNodeAddTabBar()
16055
// - DockNodeRemoveTabBar()
16056
// - DockNodeIsDropAllowedOne()
16057
// - DockNodeIsDropAllowed()
16058
// - DockNodeCalcTabBarLayout()
16059
// - DockNodeCalcSplitRects()
16060
// - DockNodeCalcDropRectsAndTestMousePos()
16061
// - DockNodePreviewDockSetup()
16062
// - DockNodePreviewDockRender()
16063
//-----------------------------------------------------------------------------
16064
16065
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16066
0
{
16067
0
    ID = id;
16068
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16069
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16070
0
    TabBar = NULL;
16071
0
    SplitAxis = ImGuiAxis_None;
16072
16073
0
    State = ImGuiDockNodeState_Unknown;
16074
0
    LastBgColor = IM_COL32_WHITE;
16075
0
    HostWindow = VisibleWindow = NULL;
16076
0
    CentralNode = OnlyNodeWithWindows = NULL;
16077
0
    CountNodeWithWindows = 0;
16078
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16079
0
    LastFocusedNodeId = 0;
16080
0
    SelectedTabId = 0;
16081
0
    WantCloseTabId = 0;
16082
0
    RefViewportId = 0;
16083
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16084
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16085
0
    IsVisible = true;
16086
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16087
0
    IsBgDrawnThisFrame = false;
16088
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16089
0
}
16090
16091
ImGuiDockNode::~ImGuiDockNode()
16092
0
{
16093
0
    IM_DELETE(TabBar);
16094
0
    TabBar = NULL;
16095
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16096
0
}
16097
16098
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16099
0
{
16100
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16101
0
    if (tab_bar == NULL)
16102
0
        return -1;
16103
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16104
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16105
0
}
16106
16107
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16108
0
{
16109
0
    window->Hidden = true;
16110
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16111
0
}
16112
16113
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16114
0
{
16115
0
    ImGuiContext& g = *GImGui; (void)g;
16116
0
    if (window->DockNode)
16117
0
    {
16118
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16119
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16120
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16121
0
    }
16122
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16123
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16124
16125
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16126
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16127
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16128
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16129
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16130
16131
0
    node->Windows.push_back(window);
16132
0
    node->WantHiddenTabBarUpdate = true;
16133
0
    window->DockNode = node;
16134
0
    window->DockId = node->ID;
16135
0
    window->DockIsActive = (node->Windows.Size > 1);
16136
0
    window->DockTabWantClose = false;
16137
16138
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16139
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16140
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16141
0
    {
16142
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16143
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16144
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16145
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16146
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16147
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16148
0
    }
16149
16150
    // Add to tab bar if requested
16151
0
    if (add_to_tab_bar)
16152
0
    {
16153
0
        if (node->TabBar == NULL)
16154
0
        {
16155
0
            DockNodeAddTabBar(node);
16156
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16157
16158
            // Add existing windows
16159
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16160
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16161
0
        }
16162
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16163
0
    }
16164
16165
0
    DockNodeUpdateVisibleFlag(node);
16166
16167
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16168
0
    if (node->HostWindow)
16169
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16170
0
}
16171
16172
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16173
0
{
16174
0
    ImGuiContext& g = *GImGui;
16175
0
    IM_ASSERT(window->DockNode == node);
16176
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16177
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16178
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16179
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16180
16181
0
    window->DockNode = NULL;
16182
0
    window->DockIsActive = window->DockTabWantClose = false;
16183
0
    window->DockId = save_dock_id;
16184
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16185
0
    if (window->ParentWindow)
16186
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16187
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16188
16189
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16190
0
    {
16191
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16192
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16193
0
        window->Viewport = NULL;
16194
0
        window->ViewportId = 0;
16195
0
        window->ViewportOwned = false;
16196
0
        window->Hidden = true;
16197
0
    }
16198
16199
    // Remove window
16200
0
    bool erased = false;
16201
0
    for (int n = 0; n < node->Windows.Size; n++)
16202
0
        if (node->Windows[n] == window)
16203
0
        {
16204
0
            node->Windows.erase(node->Windows.Data + n);
16205
0
            erased = true;
16206
0
            break;
16207
0
        }
16208
0
    if (!erased)
16209
0
        IM_ASSERT(erased);
16210
0
    if (node->VisibleWindow == window)
16211
0
        node->VisibleWindow = NULL;
16212
16213
    // Remove tab and possibly tab bar
16214
0
    node->WantHiddenTabBarUpdate = true;
16215
0
    if (node->TabBar)
16216
0
    {
16217
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16218
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16219
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16220
0
            DockNodeRemoveTabBar(node);
16221
0
    }
16222
16223
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16224
0
    {
16225
        // Automatic dock node delete themselves if they are not holding at least one tab
16226
0
        DockContextRemoveNode(&g, node, true);
16227
0
        return;
16228
0
    }
16229
16230
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16231
0
    {
16232
0
        ImGuiWindow* remaining_window = node->Windows[0];
16233
        // Note: we used to transport viewport ownership here.
16234
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16235
0
    }
16236
16237
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16238
0
    DockNodeUpdateVisibleFlag(node);
16239
0
}
16240
16241
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16242
0
{
16243
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16244
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16245
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16246
0
    if (dst_node->ChildNodes[0])
16247
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16248
0
    if (dst_node->ChildNodes[1])
16249
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16250
0
    dst_node->SplitAxis = src_node->SplitAxis;
16251
0
    dst_node->SizeRef = src_node->SizeRef;
16252
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16253
0
}
16254
16255
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16256
0
{
16257
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16258
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16259
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16260
0
    if (src_tab_bar != NULL)
16261
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16262
16263
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16264
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16265
0
    if (move_tab_bar)
16266
0
    {
16267
0
        dst_node->TabBar = src_node->TabBar;
16268
0
        src_node->TabBar = NULL;
16269
0
    }
16270
16271
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16272
0
    for (ImGuiWindow* window : src_node->Windows)
16273
0
    {
16274
0
        window->DockNode = NULL;
16275
0
        window->DockIsActive = false;
16276
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16277
0
    }
16278
0
    src_node->Windows.clear();
16279
16280
0
    if (!move_tab_bar && src_node->TabBar)
16281
0
    {
16282
0
        if (dst_node->TabBar)
16283
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16284
0
        DockNodeRemoveTabBar(src_node);
16285
0
    }
16286
0
}
16287
16288
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16289
0
{
16290
0
    for (ImGuiWindow* window : node->Windows)
16291
0
    {
16292
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16293
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
16294
0
    }
16295
0
}
16296
16297
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16298
0
{
16299
0
    if (node->HostWindow)
16300
0
    {
16301
0
        if (node->HostWindow->DockNodeAsHost == node)
16302
0
            node->HostWindow->DockNodeAsHost = NULL;
16303
0
        node->HostWindow = NULL;
16304
0
    }
16305
16306
0
    if (node->Windows.Size == 1)
16307
0
    {
16308
0
        node->VisibleWindow = node->Windows[0];
16309
0
        node->Windows[0]->DockIsActive = false;
16310
0
    }
16311
16312
0
    if (node->TabBar)
16313
0
        DockNodeRemoveTabBar(node);
16314
0
}
16315
16316
// Search function called once by root node in DockNodeUpdate()
16317
struct ImGuiDockNodeTreeInfo
16318
{
16319
    ImGuiDockNode*      CentralNode;
16320
    ImGuiDockNode*      FirstNodeWithWindows;
16321
    int                 CountNodesWithWindows;
16322
    //ImGuiWindowClass  WindowClassForMerges;
16323
16324
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16325
};
16326
16327
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16328
0
{
16329
0
    if (node->Windows.Size > 0)
16330
0
    {
16331
0
        if (info->FirstNodeWithWindows == NULL)
16332
0
            info->FirstNodeWithWindows = node;
16333
0
        info->CountNodesWithWindows++;
16334
0
    }
16335
0
    if (node->IsCentralNode())
16336
0
    {
16337
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
16338
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16339
0
        info->CentralNode = node;
16340
0
    }
16341
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16342
0
        return;
16343
0
    if (node->ChildNodes[0])
16344
0
        DockNodeFindInfo(node->ChildNodes[0], info);
16345
0
    if (node->ChildNodes[1])
16346
0
        DockNodeFindInfo(node->ChildNodes[1], info);
16347
0
}
16348
16349
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16350
0
{
16351
0
    IM_ASSERT(id != 0);
16352
0
    for (ImGuiWindow* window : node->Windows)
16353
0
        if (window->ID == id)
16354
0
            return window;
16355
0
    return NULL;
16356
0
}
16357
16358
// - Remove inactive windows/nodes.
16359
// - Update visibility flag.
16360
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16361
0
{
16362
0
    ImGuiContext& g = *GImGui;
16363
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16364
16365
    // Inherit most flags
16366
0
    if (node->ParentNode)
16367
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16368
16369
    // Recurse into children
16370
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16371
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16372
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16373
0
    node->HasCentralNodeChild = false;
16374
0
    if (node->ChildNodes[0])
16375
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16376
0
    if (node->ChildNodes[1])
16377
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16378
16379
    // Remove inactive windows, collapse nodes
16380
    // Merge node flags overrides stored in windows
16381
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16382
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16383
0
    {
16384
0
        ImGuiWindow* window = node->Windows[window_n];
16385
0
        IM_ASSERT(window->DockNode == node);
16386
16387
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16388
0
        bool remove = false;
16389
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16390
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
16391
0
        remove |= (window->DockTabWantClose);
16392
0
        if (remove)
16393
0
        {
16394
0
            window->DockTabWantClose = false;
16395
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
16396
0
            {
16397
0
                DockNodeHideHostWindow(node);
16398
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16399
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16400
0
                return;
16401
0
            }
16402
0
            DockNodeRemoveWindow(node, window, node->ID);
16403
0
            window_n--;
16404
0
            continue;
16405
0
        }
16406
16407
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16408
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16409
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16410
0
    }
16411
0
    node->UpdateMergedFlags();
16412
16413
    // Auto-hide tab bar option
16414
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16415
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16416
0
        node->WantHiddenTabBarToggle = true;
16417
0
    node->WantHiddenTabBarUpdate = false;
16418
16419
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16420
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16421
0
        node->WantHiddenTabBarToggle = false;
16422
16423
    // Apply toggles at a single point of the frame (here!)
16424
0
    if (node->Windows.Size > 1)
16425
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16426
0
    else if (node->WantHiddenTabBarToggle)
16427
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16428
0
    node->WantHiddenTabBarToggle = false;
16429
16430
0
    DockNodeUpdateVisibleFlag(node);
16431
0
}
16432
16433
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16434
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16435
0
{
16436
0
    node->HasCentralNodeChild = false;
16437
0
    if (node->ChildNodes[0])
16438
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16439
0
    if (node->ChildNodes[1])
16440
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16441
0
    if (node->IsRootNode())
16442
0
    {
16443
0
        ImGuiDockNode* mark_node = node->CentralNode;
16444
0
        while (mark_node)
16445
0
        {
16446
0
            mark_node->HasCentralNodeChild = true;
16447
0
            mark_node = mark_node->ParentNode;
16448
0
        }
16449
0
    }
16450
0
}
16451
16452
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16453
0
{
16454
    // Update visibility flag
16455
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16456
0
    is_visible |= (node->Windows.Size > 0);
16457
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16458
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16459
0
    node->IsVisible = is_visible;
16460
0
}
16461
16462
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16463
0
{
16464
0
    ImGuiContext& g = *GImGui;
16465
0
    IM_ASSERT(node->WantMouseMove == true);
16466
0
    StartMouseMovingWindow(window);
16467
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16468
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16469
0
    node->WantMouseMove = false;
16470
0
}
16471
16472
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16473
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16474
0
{
16475
0
    DockNodeUpdateFlagsAndCollapse(node);
16476
16477
    // - Setup central node pointers
16478
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16479
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16480
0
    ImGuiDockNodeTreeInfo info;
16481
0
    DockNodeFindInfo(node, &info);
16482
0
    node->CentralNode = info.CentralNode;
16483
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16484
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16485
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16486
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16487
16488
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16489
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16490
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16491
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16492
0
    {
16493
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16494
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16495
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16496
0
            {
16497
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16498
0
                break;
16499
0
            }
16500
0
    }
16501
16502
0
    ImGuiDockNode* mark_node = node->CentralNode;
16503
0
    while (mark_node)
16504
0
    {
16505
0
        mark_node->HasCentralNodeChild = true;
16506
0
        mark_node = mark_node->ParentNode;
16507
0
    }
16508
0
}
16509
16510
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16511
0
{
16512
    // Remove ourselves from any previous different host window
16513
    // This can happen if a user mistakenly does (see #4295 for details):
16514
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16515
    //  - N+1: NewFrame()                   // will create floating host window for that node
16516
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16517
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16518
0
        node->HostWindow->DockNodeAsHost = NULL;
16519
16520
0
    host_window->DockNodeAsHost = node;
16521
0
    node->HostWindow = host_window;
16522
0
}
16523
16524
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16525
0
{
16526
0
    ImGuiContext& g = *GImGui;
16527
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16528
0
    node->LastFrameAlive = g.FrameCount;
16529
0
    node->IsBgDrawnThisFrame = false;
16530
16531
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16532
0
    if (node->IsRootNode())
16533
0
        DockNodeUpdateForRootNode(node);
16534
16535
    // Remove tab bar if not needed
16536
0
    if (node->TabBar && node->IsNoTabBar())
16537
0
        DockNodeRemoveTabBar(node);
16538
16539
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16540
0
    bool want_to_hide_host_window = false;
16541
0
    if (node->IsFloatingNode())
16542
0
    {
16543
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16544
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16545
0
                want_to_hide_host_window = true;
16546
0
        if (node->CountNodeWithWindows == 0)
16547
0
            want_to_hide_host_window = true;
16548
0
    }
16549
0
    if (want_to_hide_host_window)
16550
0
    {
16551
0
        if (node->Windows.Size == 1)
16552
0
        {
16553
            // Floating window pos/size is authoritative
16554
0
            ImGuiWindow* single_window = node->Windows[0];
16555
0
            node->Pos = single_window->Pos;
16556
0
            node->Size = single_window->SizeFull;
16557
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16558
16559
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16560
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16561
0
                FocusWindow(single_window);
16562
0
            if (node->HostWindow)
16563
0
            {
16564
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16565
0
                single_window->Viewport = node->HostWindow->Viewport;
16566
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16567
0
                if (node->HostWindow->ViewportOwned)
16568
0
                {
16569
0
                    single_window->Viewport->ID = single_window->ID;
16570
0
                    single_window->Viewport->Window = single_window;
16571
0
                    single_window->ViewportOwned = true;
16572
0
                }
16573
0
            }
16574
0
            node->RefViewportId = single_window->ViewportId;
16575
0
        }
16576
16577
0
        DockNodeHideHostWindow(node);
16578
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16579
0
        node->WantCloseAll = false;
16580
0
        node->WantCloseTabId = 0;
16581
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16582
0
        node->LastFrameActive = g.FrameCount;
16583
16584
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16585
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16586
0
        return;
16587
0
    }
16588
16589
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16590
    // while the expected visible window is resizing itself.
16591
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16592
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16593
    //   N+0: Begin(): window created (with no known size), node is created
16594
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16595
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16596
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16597
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16598
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16599
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16600
0
    {
16601
0
        IM_ASSERT(node->Windows.Size > 0);
16602
0
        ImGuiWindow* ref_window = NULL;
16603
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16604
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16605
0
        if (ref_window == NULL)
16606
0
            ref_window = node->Windows[0];
16607
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16608
0
        {
16609
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16610
0
            return;
16611
0
        }
16612
0
    }
16613
16614
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16615
16616
    // Decide if the node will have a close button and a window menu button
16617
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16618
0
    node->HasCloseButton = false;
16619
0
    for (ImGuiWindow* window : node->Windows)
16620
0
    {
16621
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16622
0
        node->HasCloseButton |= window->HasCloseButton;
16623
0
        window->DockIsActive = (node->Windows.Size > 1);
16624
0
    }
16625
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16626
0
        node->HasCloseButton = false;
16627
16628
    // Bind or create host window
16629
0
    ImGuiWindow* host_window = NULL;
16630
0
    bool beginned_into_host_window = false;
16631
0
    if (node->IsDockSpace())
16632
0
    {
16633
        // [Explicit root dockspace node]
16634
0
        IM_ASSERT(node->HostWindow);
16635
0
        host_window = node->HostWindow;
16636
0
    }
16637
0
    else
16638
0
    {
16639
        // [Automatic root or child nodes]
16640
0
        if (node->IsRootNode() && node->IsVisible)
16641
0
        {
16642
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16643
16644
            // Sync Pos
16645
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16646
0
                SetNextWindowPos(ref_window->Pos);
16647
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16648
0
                SetNextWindowPos(node->Pos);
16649
16650
            // Sync Size
16651
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16652
0
                SetNextWindowSize(ref_window->SizeFull);
16653
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16654
0
                SetNextWindowSize(node->Size);
16655
16656
            // Sync Collapsed
16657
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16658
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16659
16660
            // Sync Viewport
16661
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16662
0
                SetNextWindowViewport(ref_window->ViewportId);
16663
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
16664
0
                SetNextWindowViewport(node->RefViewportId);
16665
16666
0
            SetNextWindowClass(&node->WindowClass);
16667
16668
            // Begin into the host window
16669
0
            char window_label[20];
16670
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16671
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16672
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16673
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16674
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16675
16676
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16677
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16678
0
            Begin(window_label, NULL, window_flags);
16679
0
            PopStyleVar();
16680
0
            beginned_into_host_window = true;
16681
16682
0
            host_window = g.CurrentWindow;
16683
0
            DockNodeSetupHostWindow(node, host_window);
16684
0
            host_window->DC.CursorPos = host_window->Pos;
16685
0
            node->Pos = host_window->Pos;
16686
0
            node->Size = host_window->Size;
16687
16688
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16689
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16690
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16691
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16692
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16693
            // after the dock host window, losing their top-most status.
16694
0
            if (node->HostWindow->Appearing)
16695
0
                BringWindowToDisplayFront(node->HostWindow);
16696
16697
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16698
0
        }
16699
0
        else if (node->ParentNode)
16700
0
        {
16701
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16702
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16703
0
        }
16704
0
        if (node->WantMouseMove && node->HostWindow)
16705
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16706
0
    }
16707
0
    node->RefViewportId = 0; // Clear when we have a host window
16708
16709
    // Update focused node (the one whose title bar is highlight) within a node tree
16710
0
    if (node->IsSplitNode())
16711
0
        IM_ASSERT(node->TabBar == NULL);
16712
0
    if (node->IsRootNode())
16713
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16714
0
            while (p_window != NULL && p_window->DockNode != NULL)
16715
0
            {
16716
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16717
0
                if (p_node == node)
16718
0
                {
16719
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16720
0
                    break;
16721
0
                }
16722
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16723
0
            }
16724
16725
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16726
0
    ImGuiDockNode* central_node = node->CentralNode;
16727
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16728
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16729
0
    if (central_node_hole)
16730
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16731
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16732
0
                central_node_hole_register_hit_test_hole = false;
16733
0
    if (central_node_hole_register_hit_test_hole)
16734
0
    {
16735
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16736
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16737
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16738
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16739
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16740
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16741
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16742
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16743
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16744
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16745
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16746
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16747
0
        if (central_node_hole && !hole_rect.IsInverted())
16748
0
        {
16749
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16750
0
            if (host_window->ParentWindow)
16751
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16752
0
        }
16753
0
    }
16754
16755
    // Update position/size, process and draw resizing splitters
16756
0
    if (node->IsRootNode() && host_window)
16757
0
    {
16758
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16759
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
16760
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
16761
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
16762
0
        DockNodeTreeUpdateSplitter(node);
16763
0
        PopStyleColor(3);
16764
0
    }
16765
16766
    // Draw empty node background (currently can only be the Central Node)
16767
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16768
0
    {
16769
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16770
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16771
0
        if (node->LastBgColor != 0)
16772
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16773
0
        node->IsBgDrawnThisFrame = true;
16774
0
    }
16775
16776
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16777
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16778
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16779
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16780
0
    if (render_dockspace_bg && node->IsVisible)
16781
0
    {
16782
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16783
0
        if (central_node_hole)
16784
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16785
0
        else
16786
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16787
0
    }
16788
16789
    // Draw and populate Tab Bar
16790
0
    if (host_window)
16791
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16792
0
    if (host_window && node->Windows.Size > 0)
16793
0
    {
16794
0
        DockNodeUpdateTabBar(node, host_window);
16795
0
    }
16796
0
    else
16797
0
    {
16798
0
        node->WantCloseAll = false;
16799
0
        node->WantCloseTabId = 0;
16800
0
        node->IsFocused = false;
16801
0
    }
16802
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16803
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16804
0
    else if (node->Windows.Size > 0)
16805
0
        node->SelectedTabId = node->Windows[0]->TabId;
16806
16807
    // Draw payload drop target
16808
0
    if (host_window && node->IsVisible)
16809
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16810
0
            BeginDockableDragDropTarget(host_window);
16811
16812
    // We update this after DockNodeUpdateTabBar()
16813
0
    node->LastFrameActive = g.FrameCount;
16814
16815
    // Recurse into children
16816
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16817
0
    if (host_window)
16818
0
    {
16819
0
        if (node->ChildNodes[0])
16820
0
            DockNodeUpdate(node->ChildNodes[0]);
16821
0
        if (node->ChildNodes[1])
16822
0
            DockNodeUpdate(node->ChildNodes[1]);
16823
16824
        // Render outer borders last (after the tab bar)
16825
0
        if (node->IsRootNode())
16826
0
            RenderWindowOuterBorders(host_window);
16827
0
    }
16828
16829
    // End host window
16830
0
    if (beginned_into_host_window) //-V1020
16831
0
        End();
16832
0
}
16833
16834
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16835
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16836
0
{
16837
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16838
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16839
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16840
0
        return d;
16841
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16842
0
}
16843
16844
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16845
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16846
// Custom overrides may want to decorate, group, sort entries.
16847
// Please note those are internal structures: if you copy this expect occasional breakage.
16848
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
16849
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16850
0
{
16851
0
    IM_UNUSED(ctx);
16852
0
    if (tab_bar->Tabs.Size == 1)
16853
0
    {
16854
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16855
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16856
0
            node->WantHiddenTabBarToggle = true;
16857
0
    }
16858
0
    else
16859
0
    {
16860
        // Display a selectable list of windows in this docking node
16861
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16862
0
        {
16863
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16864
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16865
0
                continue;
16866
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16867
0
                TabBarQueueFocus(tab_bar, tab);
16868
0
            SameLine();
16869
0
            Text("   ");
16870
0
        }
16871
0
    }
16872
0
}
16873
16874
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16875
0
{
16876
    // Try to position the menu so it is more likely to stays within the same viewport
16877
0
    ImGuiContext& g = *GImGui;
16878
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16879
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16880
0
    else
16881
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16882
0
    if (BeginPopup("#WindowMenu"))
16883
0
    {
16884
0
        node->IsFocused = true;
16885
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16886
0
        EndPopup();
16887
0
    }
16888
0
}
16889
16890
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16891
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16892
0
{
16893
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16894
0
        return false;
16895
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16896
0
        return false;
16897
0
    if (node->TabBar->ID == 0)
16898
0
        return false;
16899
0
    Begin(node->HostWindow->Name);
16900
0
    PushOverrideID(node->ID);
16901
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
16902
0
    IM_UNUSED(ret);
16903
0
    IM_ASSERT(ret);
16904
0
    return true;
16905
0
}
16906
16907
void ImGui::DockNodeEndAmendTabBar()
16908
0
{
16909
0
    EndTabBar();
16910
0
    PopID();
16911
0
    End();
16912
0
}
16913
16914
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16915
0
{
16916
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16917
0
    ImGuiContext& g = *GImGui;
16918
0
    if (g.NavWindowingTarget)
16919
0
        return (g.NavWindowingTarget->DockNode == node);
16920
16921
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16922
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16923
0
    {
16924
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16925
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16926
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16927
0
            parent_window = parent_window->ParentWindow->RootWindow;
16928
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16929
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16930
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16931
0
                return true;
16932
0
    }
16933
0
    return false;
16934
0
}
16935
16936
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16937
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16938
0
{
16939
0
    ImGuiContext& g = *GImGui;
16940
0
    ImGuiStyle& style = g.Style;
16941
16942
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16943
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16944
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16945
0
    node->WantCloseAll = false;
16946
0
    node->WantCloseTabId = 0;
16947
16948
    // Decide if we should use a focused title bar color
16949
0
    bool is_focused = false;
16950
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16951
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16952
0
        is_focused = true;
16953
16954
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16955
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16956
0
    {
16957
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16958
0
        node->IsFocused = is_focused;
16959
0
        if (is_focused)
16960
0
            node->LastFrameFocused = g.FrameCount;
16961
0
        if (node->VisibleWindow)
16962
0
        {
16963
            // Notify root of visible window (used to display title in OS task bar)
16964
0
            if (is_focused || root_node->VisibleWindow == NULL)
16965
0
                root_node->VisibleWindow = node->VisibleWindow;
16966
0
            if (node->TabBar)
16967
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16968
0
        }
16969
0
        return;
16970
0
    }
16971
16972
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16973
0
    bool backup_skip_item = host_window->SkipItems;
16974
0
    if (!node->IsDockSpace())
16975
0
    {
16976
0
        host_window->SkipItems = false;
16977
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16978
0
    }
16979
16980
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16981
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16982
    // as docked windows themselves will override the stack with their own root ID.
16983
0
    PushOverrideID(node->ID);
16984
0
    ImGuiTabBar* tab_bar = node->TabBar;
16985
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16986
0
    if (tab_bar == NULL)
16987
0
    {
16988
0
        DockNodeAddTabBar(node);
16989
0
        tab_bar = node->TabBar;
16990
0
    }
16991
16992
0
    ImGuiID focus_tab_id = 0;
16993
0
    node->IsFocused = is_focused;
16994
16995
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16996
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16997
16998
    // In a dock node, the Collapse Button turns into the Window Menu button.
16999
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17000
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17001
0
    {
17002
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17003
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17004
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17005
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17006
0
        is_focused |= node->IsFocused;
17007
0
    }
17008
17009
    // Layout
17010
0
    ImRect title_bar_rect, tab_bar_rect;
17011
0
    ImVec2 window_menu_button_pos;
17012
0
    ImVec2 close_button_pos;
17013
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17014
17015
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17016
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17017
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17018
0
    {
17019
0
        ImGuiWindow* window = node->Windows[window_n];
17020
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17021
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17022
0
    }
17023
17024
    // Title bar
17025
0
    if (is_focused)
17026
0
        node->LastFrameFocused = g.FrameCount;
17027
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17028
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17029
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17030
17031
    // Docking/Collapse button
17032
0
    if (has_window_menu_button)
17033
0
    {
17034
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17035
0
            OpenPopup("#WindowMenu");
17036
0
        if (IsItemActive())
17037
0
            focus_tab_id = tab_bar->SelectedTabId;
17038
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17039
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17040
0
    }
17041
17042
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17043
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17044
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17045
0
    {
17046
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17047
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17048
0
        tabs_unsorted_start = tab_n;
17049
0
    }
17050
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17051
0
    {
17052
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17053
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17054
0
        {
17055
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17056
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17057
0
        }
17058
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17059
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17060
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17061
0
    }
17062
17063
    // Apply NavWindow focus back to the tab bar
17064
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17065
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17066
17067
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17068
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17069
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17070
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17071
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17072
17073
    // Begin tab bar
17074
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17075
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17076
0
    if (!host_window->Collapsed && is_focused)
17077
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17078
0
    tab_bar->ID = GetID("#TabBar");
17079
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17080
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17081
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17082
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17083
17084
    // Backup style colors
17085
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17086
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17087
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17088
17089
    // Submit actual tabs
17090
0
    node->VisibleWindow = NULL;
17091
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17092
0
    {
17093
0
        ImGuiWindow* window = node->Windows[window_n];
17094
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17095
0
            continue;
17096
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17097
0
        {
17098
0
            ImGuiTabItemFlags tab_item_flags = 0;
17099
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17100
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17101
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17102
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17103
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17104
17105
            // Apply stored style overrides for the window
17106
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17107
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17108
17109
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17110
0
            bool tab_open = true;
17111
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17112
0
            if (!tab_open)
17113
0
                node->WantCloseTabId = window->TabId;
17114
0
            if (tab_bar->VisibleTabId == window->TabId)
17115
0
                node->VisibleWindow = window;
17116
17117
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17118
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17119
0
            window->DockTabItemRect = g.LastItemData.Rect;
17120
17121
            // Update navigation ID on menu layer
17122
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17123
0
                host_window->NavLastIds[1] = window->TabId;
17124
0
        }
17125
0
    }
17126
17127
    // Restore style colors
17128
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17129
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17130
17131
    // Notify root of visible window (used to display title in OS task bar)
17132
0
    if (node->VisibleWindow)
17133
0
        if (is_focused || root_node->VisibleWindow == NULL)
17134
0
            root_node->VisibleWindow = node->VisibleWindow;
17135
17136
    // Close button (after VisibleWindow was updated)
17137
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17138
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17139
0
    const bool close_button_is_visible = node->HasCloseButton;
17140
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17141
0
    if (close_button_is_visible)
17142
0
    {
17143
0
        if (!close_button_is_enabled)
17144
0
        {
17145
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17146
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17147
0
        }
17148
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17149
0
        {
17150
0
            node->WantCloseAll = true;
17151
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17152
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17153
0
        }
17154
        //if (IsItemActive())
17155
        //    focus_tab_id = tab_bar->SelectedTabId;
17156
0
        if (!close_button_is_enabled)
17157
0
        {
17158
0
            PopStyleColor();
17159
0
            PopItemFlag();
17160
0
        }
17161
0
    }
17162
17163
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17164
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17165
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17166
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17167
0
    {
17168
        // AllowOverlap mode required for appending into dock node tab bar,
17169
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17170
0
        bool held;
17171
0
        KeepAliveID(title_bar_id);
17172
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17173
0
        if (g.HoveredId == title_bar_id)
17174
0
        {
17175
0
            g.LastItemData.ID = title_bar_id;
17176
0
        }
17177
0
        if (held)
17178
0
        {
17179
0
            if (IsMouseClicked(0))
17180
0
                focus_tab_id = tab_bar->SelectedTabId;
17181
17182
            // Forward moving request to selected window
17183
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17184
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17185
0
        }
17186
0
    }
17187
17188
    // Forward focus from host node to selected window
17189
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17190
    //    focus_tab_id = tab_bar->SelectedTabId;
17191
17192
    // When clicked on a tab we requested focus to the docked child
17193
    // This overrides the value set by "forward focus from host node to selected window".
17194
0
    if (tab_bar->NextSelectedTabId)
17195
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17196
17197
    // Apply navigation focus
17198
0
    if (focus_tab_id != 0)
17199
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17200
0
            if (tab->Window)
17201
0
            {
17202
0
                FocusWindow(tab->Window);
17203
0
                NavInitWindow(tab->Window, false);
17204
0
            }
17205
17206
0
    EndTabBar();
17207
0
    PopID();
17208
17209
    // Restore SkipItems flag
17210
0
    if (!node->IsDockSpace())
17211
0
    {
17212
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17213
0
        host_window->SkipItems = backup_skip_item;
17214
0
    }
17215
0
}
17216
17217
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17218
0
{
17219
0
    IM_ASSERT(node->TabBar == NULL);
17220
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17221
0
}
17222
17223
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17224
0
{
17225
0
    if (node->TabBar == NULL)
17226
0
        return;
17227
0
    IM_DELETE(node->TabBar);
17228
0
    node->TabBar = NULL;
17229
0
}
17230
17231
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17232
0
{
17233
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17234
0
        return false;
17235
17236
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17237
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17238
0
    if (host_class->ClassId != payload_class->ClassId)
17239
0
    {
17240
0
        bool pass = false;
17241
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17242
0
            pass = true;
17243
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17244
0
            pass = true;
17245
0
        if (!pass)
17246
0
            return false;
17247
0
    }
17248
17249
    // Prevent docking any window created above a popup
17250
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17251
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17252
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17253
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17254
0
    ImGuiContext& g = *GImGui;
17255
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17256
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17257
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17258
0
                return false;
17259
17260
0
    return true;
17261
0
}
17262
17263
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
17264
0
{
17265
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
17266
0
        return true;
17267
17268
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17269
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17270
0
    {
17271
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17272
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
17273
0
            return true;
17274
0
    }
17275
0
    return false;
17276
0
}
17277
17278
// window menu button == collapse button when not in a dock node.
17279
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17280
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17281
0
{
17282
0
    ImGuiContext& g = *GImGui;
17283
0
    ImGuiStyle& style = g.Style;
17284
17285
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17286
0
    if (out_title_rect) { *out_title_rect = r; }
17287
17288
0
    r.Min.x += style.WindowBorderSize;
17289
0
    r.Max.x -= style.WindowBorderSize;
17290
17291
0
    float button_sz = g.FontSize;
17292
0
    r.Min.x += style.FramePadding.x;
17293
0
    r.Max.x -= style.FramePadding.x;
17294
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
17295
0
    if (node->HasCloseButton)
17296
0
    {
17297
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17298
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17299
0
    }
17300
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17301
0
    {
17302
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17303
0
    }
17304
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17305
0
    {
17306
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
17307
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
17308
0
    }
17309
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17310
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17311
0
}
17312
17313
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17314
0
{
17315
0
    ImGuiContext& g = *GImGui;
17316
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
17317
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17318
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
17319
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
17320
17321
    // Distribute size on given axis (with a desired size or equally)
17322
0
    const float w_avail = size_old[axis] - dock_spacing;
17323
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17324
0
    {
17325
0
        size_new[axis] = size_new_desired[axis];
17326
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17327
0
    }
17328
0
    else
17329
0
    {
17330
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
17331
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
17332
0
    }
17333
17334
    // Position each node
17335
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17336
0
    {
17337
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17338
0
    }
17339
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17340
0
    {
17341
0
        pos_new[axis] = pos_old[axis];
17342
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17343
0
    }
17344
0
}
17345
17346
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17347
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17348
0
{
17349
0
    ImGuiContext& g = *GImGui;
17350
17351
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17352
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17353
0
    float hs_w; // Half-size, longer axis
17354
0
    float hs_h; // Half-size, smaller axis
17355
0
    ImVec2 off; // Distance from edge or center
17356
0
    if (outer_docking)
17357
0
    {
17358
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17359
        //hs_h = ImTrunc(hs_w * 0.15f);
17360
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17361
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
17362
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
17363
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
17364
0
    }
17365
0
    else
17366
0
    {
17367
0
        hs_w = ImTrunc(hs_for_central_nodes);
17368
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
17369
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
17370
0
    }
17371
17372
0
    ImVec2 c = ImTrunc(parent.GetCenter());
17373
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
17374
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17375
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17376
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17377
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17378
17379
0
    if (test_mouse_pos == NULL)
17380
0
        return false;
17381
17382
0
    ImRect hit_r = out_r;
17383
0
    if (!outer_docking)
17384
0
    {
17385
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17386
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
17387
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
17388
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17389
0
        float r_threshold_center = hs_w * 1.4f;
17390
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
17391
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17392
0
            return (dir == ImGuiDir_None);
17393
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17394
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17395
0
    }
17396
0
    return hit_r.Contains(*test_mouse_pos);
17397
0
}
17398
17399
// host_node may be NULL if the window doesn't have a DockNode already.
17400
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17401
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17402
0
{
17403
0
    ImGuiContext& g = *GImGui;
17404
17405
    // There is an edge case when docking into a dockspace which only has inactive nodes.
17406
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17407
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17408
0
    if (payload_node == NULL)
17409
0
        payload_node = payload_window->DockNodeAsHost;
17410
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17411
0
    if (ref_node_for_rect)
17412
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
17413
17414
    // Filter, figure out where we are allowed to dock
17415
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17416
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17417
0
    data->IsCenterAvailable = true;
17418
0
    if (is_outer_docking)
17419
0
        data->IsCenterAvailable = false;
17420
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17421
0
        data->IsCenterAvailable = false;
17422
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
17423
0
        data->IsCenterAvailable = false;
17424
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17425
0
        data->IsCenterAvailable = false;
17426
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17427
0
        data->IsCenterAvailable = false;
17428
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17429
0
        data->IsCenterAvailable = false;
17430
17431
0
    data->IsSidesAvailable = true;
17432
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
17433
0
        data->IsSidesAvailable = false;
17434
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17435
0
        data->IsSidesAvailable = false;
17436
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
17437
0
        data->IsSidesAvailable = false;
17438
17439
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17440
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17441
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17442
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17443
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17444
17445
    // Calculate drop shapes geometry for allowed splitting directions
17446
0
    IM_ASSERT(ImGuiDir_None == -1);
17447
0
    data->SplitNode = host_node;
17448
0
    data->SplitDir = ImGuiDir_None;
17449
0
    data->IsSplitDirExplicit = false;
17450
0
    if (!host_window->Collapsed)
17451
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17452
0
        {
17453
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17454
0
                continue;
17455
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17456
0
                continue;
17457
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17458
0
            {
17459
0
                data->SplitDir = (ImGuiDir)dir;
17460
0
                data->IsSplitDirExplicit = true;
17461
0
            }
17462
0
        }
17463
17464
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17465
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17466
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17467
0
        data->IsDropAllowed = false;
17468
17469
    // Calculate split area
17470
0
    data->SplitRatio = 0.0f;
17471
0
    if (data->SplitDir != ImGuiDir_None)
17472
0
    {
17473
0
        ImGuiDir split_dir = data->SplitDir;
17474
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17475
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17476
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17477
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17478
17479
        // Calculate split ratio so we can pass it down the docking request
17480
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17481
0
        data->FutureNode.Pos = pos_new;
17482
0
        data->FutureNode.Size = size_new;
17483
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17484
0
    }
17485
0
}
17486
17487
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17488
0
{
17489
0
    ImGuiContext& g = *GImGui;
17490
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17491
17492
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17493
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17494
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17495
17496
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17497
0
    int overlay_draw_lists_count = 0;
17498
0
    ImDrawList* overlay_draw_lists[2];
17499
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17500
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17501
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17502
17503
    // Draw main preview rectangle
17504
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17505
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17506
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17507
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17508
17509
    // Display area preview
17510
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17511
0
    if (data->IsDropAllowed)
17512
0
    {
17513
0
        ImRect overlay_rect = data->FutureNode.Rect();
17514
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17515
0
            overlay_rect.Min.y += GetFrameHeight();
17516
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17517
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17518
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
17519
0
    }
17520
17521
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17522
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17523
0
    {
17524
        // Compute target tab bar geometry so we can locate our preview tabs
17525
0
        ImRect tab_bar_rect;
17526
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17527
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17528
0
        if (host_node && host_node->TabBar)
17529
0
        {
17530
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17531
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17532
0
            else
17533
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17534
0
        }
17535
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17536
0
        {
17537
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17538
0
        }
17539
17540
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17541
0
        if (root_payload->DockNodeAsHost)
17542
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17543
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17544
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17545
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17546
0
        {
17547
            // DockNode's TabBar may have non-window Tabs manually appended by user
17548
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17549
0
            if (tab_bar_with_payload && payload_window == NULL)
17550
0
                continue;
17551
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17552
0
                continue;
17553
17554
            // Calculate the tab bounding box for each payload window
17555
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17556
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17557
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17558
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17559
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17560
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17561
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17562
0
            {
17563
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
17564
0
                if (!tab_bar_rect.Contains(tab_bb))
17565
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17566
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17567
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17568
0
                if (!tab_bar_rect.Contains(tab_bb))
17569
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17570
0
            }
17571
0
            PopStyleColor();
17572
0
        }
17573
0
    }
17574
17575
    // Display drop boxes
17576
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17577
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17578
0
    {
17579
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17580
0
        {
17581
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17582
0
            ImRect draw_r_in = draw_r;
17583
0
            draw_r_in.Expand(-2.0f);
17584
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17585
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17586
0
            {
17587
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17588
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17589
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17590
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17591
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17592
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17593
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17594
0
            }
17595
0
        }
17596
17597
        // Stop after ImGuiDir_None
17598
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
17599
0
            return;
17600
0
    }
17601
0
}
17602
17603
//-----------------------------------------------------------------------------
17604
// Docking: ImGuiDockNode Tree manipulation functions
17605
//-----------------------------------------------------------------------------
17606
// - DockNodeTreeSplit()
17607
// - DockNodeTreeMerge()
17608
// - DockNodeTreeUpdatePosSize()
17609
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17610
// - DockNodeTreeUpdateSplitter()
17611
// - DockNodeTreeFindFallbackLeafNode()
17612
// - DockNodeTreeFindNodeByPos()
17613
//-----------------------------------------------------------------------------
17614
17615
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17616
0
{
17617
0
    ImGuiContext& g = *GImGui;
17618
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17619
17620
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17621
0
    child_0->ParentNode = parent_node;
17622
17623
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17624
0
    child_1->ParentNode = parent_node;
17625
17626
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17627
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17628
0
    parent_node->ChildNodes[0] = child_0;
17629
0
    parent_node->ChildNodes[1] = child_1;
17630
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17631
0
    parent_node->SplitAxis = split_axis;
17632
0
    parent_node->VisibleWindow = NULL;
17633
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17634
17635
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
17636
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17637
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17638
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17639
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
17640
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
17641
17642
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17643
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17644
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17645
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17646
17647
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17648
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17649
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17650
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17651
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17652
0
    child_0->UpdateMergedFlags();
17653
0
    child_1->UpdateMergedFlags();
17654
0
    parent_node->UpdateMergedFlags();
17655
0
    if (child_inheritor->IsCentralNode())
17656
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17657
0
}
17658
17659
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17660
0
{
17661
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17662
0
    ImGuiContext& g = *GImGui;
17663
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17664
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17665
0
    IM_ASSERT(child_0 || child_1);
17666
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17667
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17668
0
    {
17669
0
        IM_ASSERT(parent_node->TabBar == NULL);
17670
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17671
0
    }
17672
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17673
17674
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17675
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17676
0
    if (child_0)
17677
0
    {
17678
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17679
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17680
0
    }
17681
0
    if (child_1)
17682
0
    {
17683
0
        DockNodeMoveWindows(parent_node, child_1);
17684
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17685
0
    }
17686
0
    DockNodeApplyPosSizeToWindows(parent_node);
17687
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17688
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17689
0
    parent_node->SizeRef = backup_last_explicit_size;
17690
17691
    // Flags transfer
17692
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17693
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17694
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17695
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17696
0
    parent_node->UpdateMergedFlags();
17697
17698
0
    if (child_0)
17699
0
    {
17700
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17701
0
        IM_DELETE(child_0);
17702
0
    }
17703
0
    if (child_1)
17704
0
    {
17705
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17706
0
        IM_DELETE(child_1);
17707
0
    }
17708
0
}
17709
17710
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17711
// (Depth-first, Pre-Order)
17712
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17713
0
{
17714
    // During the regular dock node update we write to all nodes.
17715
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17716
0
    ImGuiContext& g = *GImGui;
17717
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17718
0
    if (write_to_node)
17719
0
    {
17720
0
        node->Pos = pos;
17721
0
        node->Size = size;
17722
0
    }
17723
17724
0
    if (node->IsLeafNode())
17725
0
        return;
17726
17727
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17728
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17729
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17730
0
    ImVec2 child_0_size = size, child_1_size = size;
17731
17732
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17733
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17734
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17735
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17736
17737
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17738
0
    {
17739
0
        const float spacing = g.Style.DockingSeparatorSize;
17740
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17741
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17742
17743
        // Size allocation policy
17744
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17745
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17746
17747
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17748
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
17749
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17750
17751
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17752
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17753
0
        {
17754
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17755
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17756
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17757
0
        }
17758
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17759
0
        {
17760
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17761
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17762
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17763
0
        }
17764
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17765
0
        {
17766
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17767
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17768
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17769
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
17770
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17771
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17772
0
        }
17773
17774
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17775
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17776
0
        {
17777
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17778
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17779
0
        }
17780
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17781
0
        {
17782
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17783
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17784
0
        }
17785
0
        else
17786
0
        {
17787
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17788
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17789
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
17790
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17791
0
        }
17792
17793
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17794
0
    }
17795
17796
0
    if (only_write_to_single_node == NULL)
17797
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17798
17799
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17800
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17801
0
    if (child_0_recurse)
17802
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17803
0
    if (child_1_recurse)
17804
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17805
0
}
17806
17807
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17808
0
{
17809
0
    if (node->IsLeafNode())
17810
0
    {
17811
0
        touching_nodes->push_back(node);
17812
0
        return;
17813
0
    }
17814
0
    if (node->ChildNodes[0]->IsVisible)
17815
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17816
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17817
0
    if (node->ChildNodes[1]->IsVisible)
17818
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17819
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17820
0
}
17821
17822
// (Depth-First, Pre-Order)
17823
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17824
0
{
17825
0
    if (node->IsLeafNode())
17826
0
        return;
17827
17828
0
    ImGuiContext& g = *GImGui;
17829
17830
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17831
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17832
0
    if (child_0->IsVisible && child_1->IsVisible)
17833
0
    {
17834
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17835
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17836
0
        IM_ASSERT(axis != ImGuiAxis_None);
17837
0
        ImRect bb;
17838
0
        bb.Min = child_0->Pos;
17839
0
        bb.Max = child_1->Pos;
17840
0
        bb.Min[axis] += child_0->Size[axis];
17841
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17842
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17843
17844
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17845
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17846
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17847
0
        {
17848
0
            ImGuiWindow* window = g.CurrentWindow;
17849
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17850
0
        }
17851
0
        else
17852
0
        {
17853
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17854
            //bb.Max[axis] -= 1;
17855
0
            PushID(node->ID);
17856
17857
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17858
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17859
0
            float min_size = g.Style.WindowMinSize[axis];
17860
0
            float resize_limits[2];
17861
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17862
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17863
17864
0
            ImGuiID splitter_id = GetID("##Splitter");
17865
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17866
0
            {
17867
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17868
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17869
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17870
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17871
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17872
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17873
17874
                // [DEBUG] Render touching nodes & limits
17875
                /*
17876
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17877
                for (int n = 0; n < 2; n++)
17878
                {
17879
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17880
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17881
                    if (axis == ImGuiAxis_X)
17882
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17883
                    else
17884
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17885
                }
17886
                */
17887
0
            }
17888
17889
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17890
0
            float cur_size_0 = child_0->Size[axis];
17891
0
            float cur_size_1 = child_1->Size[axis];
17892
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17893
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17894
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17895
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17896
0
            {
17897
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17898
0
                {
17899
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17900
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17901
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17902
17903
                    // Lock the size of every node that is a sibling of the node we are touching
17904
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17905
0
                    for (int side_n = 0; side_n < 2; side_n++)
17906
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17907
0
                        {
17908
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17909
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17910
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17911
0
                            while (touching_node->ParentNode != node)
17912
0
                            {
17913
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17914
0
                                {
17915
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17916
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17917
0
                                    node_to_preserve->WantLockSizeOnce = true;
17918
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17919
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17920
0
                                }
17921
0
                                touching_node = touching_node->ParentNode;
17922
0
                            }
17923
0
                        }
17924
17925
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17926
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17927
0
                    MarkIniSettingsDirty();
17928
0
                }
17929
0
            }
17930
0
            PopID();
17931
0
        }
17932
0
    }
17933
17934
0
    if (child_0->IsVisible)
17935
0
        DockNodeTreeUpdateSplitter(child_0);
17936
0
    if (child_1->IsVisible)
17937
0
        DockNodeTreeUpdateSplitter(child_1);
17938
0
}
17939
17940
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17941
0
{
17942
0
    if (node->IsLeafNode())
17943
0
        return node;
17944
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17945
0
        return leaf_node;
17946
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17947
0
        return leaf_node;
17948
0
    return NULL;
17949
0
}
17950
17951
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17952
0
{
17953
0
    if (!node->IsVisible)
17954
0
        return NULL;
17955
17956
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17957
0
    ImRect r(node->Pos, node->Pos + node->Size);
17958
0
    r.Expand(dock_spacing * 0.5f);
17959
0
    bool inside = r.Contains(pos);
17960
0
    if (!inside)
17961
0
        return NULL;
17962
17963
0
    if (node->IsLeafNode())
17964
0
        return node;
17965
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17966
0
        return hovered_node;
17967
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17968
0
        return hovered_node;
17969
17970
    // This means we are hovering over the splitter/spacing of a parent node
17971
0
    return node;
17972
0
}
17973
17974
//-----------------------------------------------------------------------------
17975
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17976
//-----------------------------------------------------------------------------
17977
// - SetWindowDock() [Internal]
17978
// - DockSpace()
17979
// - DockSpaceOverViewport()
17980
//-----------------------------------------------------------------------------
17981
17982
// [Internal] Called via SetNextWindowDockID()
17983
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17984
0
{
17985
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17986
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17987
0
        return;
17988
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17989
17990
0
    if (window->DockId == dock_id)
17991
0
        return;
17992
17993
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17994
0
    ImGuiContext* ctx = GImGui;
17995
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17996
0
        if (new_node->IsSplitNode())
17997
0
        {
17998
            // Policy: Find central node or latest focused node. We first move back to our root node.
17999
0
            new_node = DockNodeGetRootNode(new_node);
18000
0
            if (new_node->CentralNode)
18001
0
            {
18002
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18003
0
                dock_id = new_node->CentralNode->ID;
18004
0
            }
18005
0
            else
18006
0
            {
18007
0
                dock_id = new_node->LastFocusedNodeId;
18008
0
            }
18009
0
        }
18010
18011
0
    if (window->DockId == dock_id)
18012
0
        return;
18013
18014
0
    if (window->DockNode)
18015
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18016
0
    window->DockId = dock_id;
18017
0
}
18018
18019
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18020
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18021
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18022
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18023
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18024
0
{
18025
0
    ImGuiContext* ctx = GImGui;
18026
0
    ImGuiContext& g = *ctx;
18027
0
    ImGuiWindow* window = GetCurrentWindowRead();
18028
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18029
0
        return 0;
18030
18031
    // Early out if parent window is hidden/collapsed
18032
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18033
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18034
0
    if (window->SkipItems)
18035
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18036
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18037
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18038
18039
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18040
0
    IM_ASSERT(id != 0);
18041
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
18042
0
    if (!node)
18043
0
    {
18044
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
18045
0
        node = DockContextAddNode(ctx, id);
18046
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18047
0
    }
18048
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18049
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
18050
0
    node->SharedFlags = flags;
18051
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18052
18053
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18054
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18055
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18056
0
    {
18057
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18058
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18059
0
        return id;
18060
0
    }
18061
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18062
18063
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18064
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18065
0
    {
18066
0
        node->LastFrameAlive = g.FrameCount;
18067
0
        return id;
18068
0
    }
18069
18070
0
    const ImVec2 content_avail = GetContentRegionAvail();
18071
0
    ImVec2 size = ImTrunc(size_arg);
18072
0
    if (size.x <= 0.0f)
18073
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18074
0
    if (size.y <= 0.0f)
18075
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18076
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18077
18078
0
    node->Pos = window->DC.CursorPos;
18079
0
    node->Size = node->SizeRef = size;
18080
0
    SetNextWindowPos(node->Pos);
18081
0
    SetNextWindowSize(node->Size);
18082
0
    g.NextWindowData.PosUndock = false;
18083
18084
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18085
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18086
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18087
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18088
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18089
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18090
18091
0
    char title[256];
18092
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
18093
18094
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18095
0
    Begin(title, NULL, window_flags);
18096
0
    PopStyleVar();
18097
18098
0
    ImGuiWindow* host_window = g.CurrentWindow;
18099
0
    DockNodeSetupHostWindow(node, host_window);
18100
0
    host_window->ChildId = window->GetID(title);
18101
0
    node->OnlyNodeWithWindows = NULL;
18102
18103
0
    IM_ASSERT(node->IsRootNode());
18104
18105
    // We need to handle the rare case were a central node is missing.
18106
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18107
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18108
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18109
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18110
    // as it doesn't make sense for an empty dockspace to not have this property.
18111
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18112
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18113
18114
    // Update the node
18115
0
    DockNodeUpdate(node);
18116
18117
0
    End();
18118
18119
0
    ImRect bb(node->Pos, node->Pos + size);
18120
0
    ItemSize(size);
18121
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18122
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18123
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18124
18125
0
    return id;
18126
0
}
18127
18128
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18129
// The limitation with this call is that your window won't have a menu bar.
18130
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18131
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18132
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18133
0
{
18134
0
    if (viewport == NULL)
18135
0
        viewport = GetMainViewport();
18136
18137
0
    SetNextWindowPos(viewport->WorkPos);
18138
0
    SetNextWindowSize(viewport->WorkSize);
18139
0
    SetNextWindowViewport(viewport->ID);
18140
18141
0
    ImGuiWindowFlags host_window_flags = 0;
18142
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18143
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18144
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18145
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18146
18147
0
    char label[32];
18148
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
18149
18150
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18151
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18152
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18153
0
    Begin(label, NULL, host_window_flags);
18154
0
    PopStyleVar(3);
18155
18156
0
    ImGuiID dockspace_id = GetID("DockSpace");
18157
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18158
0
    End();
18159
18160
0
    return dockspace_id;
18161
0
}
18162
18163
//-----------------------------------------------------------------------------
18164
// Docking: Builder Functions
18165
//-----------------------------------------------------------------------------
18166
// Very early end-user API to manipulate dock nodes.
18167
// Only available in imgui_internal.h. Expect this API to change/break!
18168
// It is expected that those functions are all called _before_ the dockspace node submission.
18169
//-----------------------------------------------------------------------------
18170
// - DockBuilderDockWindow()
18171
// - DockBuilderGetNode()
18172
// - DockBuilderSetNodePos()
18173
// - DockBuilderSetNodeSize()
18174
// - DockBuilderAddNode()
18175
// - DockBuilderRemoveNode()
18176
// - DockBuilderRemoveNodeChildNodes()
18177
// - DockBuilderRemoveNodeDockedWindows()
18178
// - DockBuilderSplitNode()
18179
// - DockBuilderCopyNodeRec()
18180
// - DockBuilderCopyNode()
18181
// - DockBuilderCopyWindowSettings()
18182
// - DockBuilderCopyDockSpace()
18183
// - DockBuilderFinish()
18184
//-----------------------------------------------------------------------------
18185
18186
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18187
0
{
18188
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18189
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18190
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18191
0
    ImGuiID window_id = ImHashStr(window_name);
18192
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18193
0
    {
18194
        // Apply to created window
18195
0
        ImGuiID prev_node_id = window->DockId;
18196
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18197
0
        if (window->DockId != prev_node_id)
18198
0
            window->DockOrder = -1;
18199
0
    }
18200
0
    else
18201
0
    {
18202
        // Apply to settings
18203
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18204
0
        if (settings == NULL)
18205
0
            settings = CreateNewWindowSettings(window_name);
18206
0
        if (settings->DockId != node_id)
18207
0
            settings->DockOrder = -1;
18208
0
        settings->DockId = node_id;
18209
0
    }
18210
0
}
18211
18212
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18213
0
{
18214
0
    ImGuiContext* ctx = GImGui;
18215
0
    return DockContextFindNodeByID(ctx, node_id);
18216
0
}
18217
18218
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18219
0
{
18220
0
    ImGuiContext* ctx = GImGui;
18221
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18222
0
    if (node == NULL)
18223
0
        return;
18224
0
    node->Pos = pos;
18225
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18226
0
}
18227
18228
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18229
0
{
18230
0
    ImGuiContext* ctx = GImGui;
18231
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18232
0
    if (node == NULL)
18233
0
        return;
18234
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18235
0
    node->Size = node->SizeRef = size;
18236
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18237
0
}
18238
18239
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18240
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18241
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18242
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18243
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18244
// - Use (id == 0) to let the system allocate a node identifier.
18245
// - Existing node with a same id will be removed.
18246
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18247
0
{
18248
0
    ImGuiContext* ctx = GImGui;
18249
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
18250
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18251
18252
0
    if (node_id != 0)
18253
0
        DockBuilderRemoveNode(node_id);
18254
18255
0
    ImGuiDockNode* node = NULL;
18256
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
18257
0
    {
18258
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
18259
0
        node = DockContextFindNodeByID(ctx, node_id);
18260
0
    }
18261
0
    else
18262
0
    {
18263
0
        node = DockContextAddNode(ctx, node_id);
18264
0
        node->SetLocalFlags(flags);
18265
0
    }
18266
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18267
0
    return node->ID;
18268
0
}
18269
18270
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18271
0
{
18272
0
    ImGuiContext* ctx = GImGui;
18273
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
18274
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18275
18276
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18277
0
    if (node == NULL)
18278
0
        return;
18279
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18280
0
    DockBuilderRemoveNodeChildNodes(node_id);
18281
    // Node may have moved or deleted if e.g. any merge happened
18282
0
    node = DockContextFindNodeByID(ctx, node_id);
18283
0
    if (node == NULL)
18284
0
        return;
18285
0
    if (node->IsCentralNode() && node->ParentNode)
18286
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18287
0
    DockContextRemoveNode(ctx, node, true);
18288
0
}
18289
18290
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18291
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18292
0
{
18293
0
    ImGuiContext* ctx = GImGui;
18294
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18295
18296
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
18297
0
    if (root_id && root_node == NULL)
18298
0
        return;
18299
0
    bool has_central_node = false;
18300
18301
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18302
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18303
18304
    // Process active windows
18305
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18306
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18307
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18308
0
        {
18309
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18310
0
            if (want_removal)
18311
0
            {
18312
0
                if (node->IsCentralNode())
18313
0
                    has_central_node = true;
18314
0
                if (root_id != 0)
18315
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
18316
0
                if (root_node)
18317
0
                {
18318
0
                    DockNodeMoveWindows(root_node, node);
18319
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18320
0
                }
18321
0
                nodes_to_remove.push_back(node);
18322
0
            }
18323
0
        }
18324
18325
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18326
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18327
0
    if (root_node)
18328
0
    {
18329
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18330
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
18331
0
    }
18332
18333
    // Apply to settings
18334
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
18335
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
18336
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
18337
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
18338
0
                {
18339
0
                    settings->DockId = root_id;
18340
0
                    break;
18341
0
                }
18342
18343
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18344
0
    if (nodes_to_remove.Size > 1)
18345
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18346
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
18347
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
18348
18349
0
    if (root_id == 0)
18350
0
    {
18351
0
        dc->Nodes.Clear();
18352
0
        dc->Requests.clear();
18353
0
    }
18354
0
    else if (has_central_node)
18355
0
    {
18356
0
        root_node->CentralNode = root_node;
18357
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18358
0
    }
18359
0
}
18360
18361
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18362
0
{
18363
    // Clear references in settings
18364
0
    ImGuiContext* ctx = GImGui;
18365
0
    ImGuiContext& g = *ctx;
18366
0
    if (clear_settings_refs)
18367
0
    {
18368
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18369
0
        {
18370
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18371
0
            if (!want_removal && settings->DockId != 0)
18372
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
18373
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
18374
0
                        want_removal = true;
18375
0
            if (want_removal)
18376
0
                settings->DockId = 0;
18377
0
        }
18378
0
    }
18379
18380
    // Clear references in windows
18381
0
    for (int n = 0; n < g.Windows.Size; n++)
18382
0
    {
18383
0
        ImGuiWindow* window = g.Windows[n];
18384
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18385
0
        if (want_removal)
18386
0
        {
18387
0
            const ImGuiID backup_dock_id = window->DockId;
18388
0
            IM_UNUSED(backup_dock_id);
18389
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
18390
0
            if (!clear_settings_refs)
18391
0
                IM_ASSERT(window->DockId == backup_dock_id);
18392
0
        }
18393
0
    }
18394
0
}
18395
18396
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18397
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18398
// FIXME-DOCK: We are not exposing nor using split_outer.
18399
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18400
0
{
18401
0
    ImGuiContext& g = *GImGui;
18402
0
    IM_ASSERT(split_dir != ImGuiDir_None);
18403
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18404
18405
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18406
0
    if (node == NULL)
18407
0
    {
18408
0
        IM_ASSERT(node != NULL);
18409
0
        return 0;
18410
0
    }
18411
18412
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18413
18414
0
    ImGuiDockRequest req;
18415
0
    req.Type = ImGuiDockRequestType_Split;
18416
0
    req.DockTargetWindow = NULL;
18417
0
    req.DockTargetNode = node;
18418
0
    req.DockPayload = NULL;
18419
0
    req.DockSplitDir = split_dir;
18420
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18421
0
    req.DockSplitOuter = false;
18422
0
    DockContextProcessDock(&g, &req);
18423
18424
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18425
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18426
0
    if (out_id_at_dir)
18427
0
        *out_id_at_dir = id_at_dir;
18428
0
    if (out_id_at_opposite_dir)
18429
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18430
0
    return id_at_dir;
18431
0
}
18432
18433
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18434
0
{
18435
0
    ImGuiContext& g = *GImGui;
18436
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18437
0
    dst_node->SharedFlags = src_node->SharedFlags;
18438
0
    dst_node->LocalFlags = src_node->LocalFlags;
18439
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18440
0
    dst_node->Pos = src_node->Pos;
18441
0
    dst_node->Size = src_node->Size;
18442
0
    dst_node->SizeRef = src_node->SizeRef;
18443
0
    dst_node->SplitAxis = src_node->SplitAxis;
18444
0
    dst_node->UpdateMergedFlags();
18445
18446
0
    out_node_remap_pairs->push_back(src_node->ID);
18447
0
    out_node_remap_pairs->push_back(dst_node->ID);
18448
18449
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18450
0
        if (src_node->ChildNodes[child_n])
18451
0
        {
18452
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18453
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18454
0
        }
18455
18456
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18457
0
    return dst_node;
18458
0
}
18459
18460
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18461
0
{
18462
0
    ImGuiContext* ctx = GImGui;
18463
0
    IM_ASSERT(src_node_id != 0);
18464
0
    IM_ASSERT(dst_node_id != 0);
18465
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18466
18467
0
    DockBuilderRemoveNode(dst_node_id);
18468
18469
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
18470
0
    IM_ASSERT(src_node != NULL);
18471
18472
0
    out_node_remap_pairs->clear();
18473
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18474
18475
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18476
0
}
18477
18478
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18479
0
{
18480
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18481
0
    if (src_window == NULL)
18482
0
        return;
18483
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18484
0
    {
18485
0
        dst_window->Pos = src_window->Pos;
18486
0
        dst_window->Size = src_window->Size;
18487
0
        dst_window->SizeFull = src_window->SizeFull;
18488
0
        dst_window->Collapsed = src_window->Collapsed;
18489
0
    }
18490
0
    else
18491
0
    {
18492
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18493
0
        if (!dst_settings)
18494
0
            dst_settings = CreateNewWindowSettings(dst_name);
18495
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18496
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18497
0
        {
18498
0
            dst_settings->ViewportPos = window_pos_2ih;
18499
0
            dst_settings->ViewportId = src_window->ViewportId;
18500
0
            dst_settings->Pos = ImVec2ih(0, 0);
18501
0
        }
18502
0
        else
18503
0
        {
18504
0
            dst_settings->Pos = window_pos_2ih;
18505
0
        }
18506
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18507
0
        dst_settings->Collapsed = src_window->Collapsed;
18508
0
    }
18509
0
}
18510
18511
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18512
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18513
0
{
18514
0
    ImGuiContext& g = *GImGui;
18515
0
    IM_ASSERT(src_dockspace_id != 0);
18516
0
    IM_ASSERT(dst_dockspace_id != 0);
18517
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18518
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18519
18520
    // Duplicate entire dock
18521
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18522
    // whereas we could attempt to at least keep them together in a new, same floating node.
18523
0
    ImVector<ImGuiID> node_remap_pairs;
18524
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18525
18526
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18527
    // (The windows associated to src_dockspace_id are staying in place)
18528
0
    ImVector<ImGuiID> src_windows;
18529
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18530
0
    {
18531
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18532
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18533
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18534
0
        src_windows.push_back(src_window_id);
18535
18536
        // Search in the remapping tables
18537
0
        ImGuiID src_dock_id = 0;
18538
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18539
0
            src_dock_id = src_window->DockId;
18540
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18541
0
            src_dock_id = src_window_settings->DockId;
18542
0
        ImGuiID dst_dock_id = 0;
18543
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18544
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18545
0
            {
18546
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18547
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18548
0
                break;
18549
0
            }
18550
18551
0
        if (dst_dock_id != 0)
18552
0
        {
18553
            // Docked windows gets redocked into the new node hierarchy.
18554
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18555
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18556
0
        }
18557
0
        else
18558
0
        {
18559
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18560
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18561
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18562
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18563
0
        }
18564
0
    }
18565
18566
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18567
    // Find those windows and move to them to the cloned dock node. This may be optional?
18568
    // Dock those are a second step as undocking would invalidate source dock nodes.
18569
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18570
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18571
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18572
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18573
0
        {
18574
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18575
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18576
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18577
0
            {
18578
0
                ImGuiWindow* window = node->Windows[window_n];
18579
0
                if (src_windows.contains(window->ID))
18580
0
                    continue;
18581
18582
                // Docked windows gets redocked into the new node hierarchy.
18583
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18584
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18585
0
            }
18586
0
        }
18587
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18588
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18589
0
}
18590
18591
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18592
void ImGui::DockBuilderFinish(ImGuiID root_id)
18593
0
{
18594
0
    ImGuiContext* ctx = GImGui;
18595
    //DockContextRebuild(ctx);
18596
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
18597
0
}
18598
18599
//-----------------------------------------------------------------------------
18600
// Docking: Begin/End Support Functions (called from Begin/End)
18601
//-----------------------------------------------------------------------------
18602
// - GetWindowAlwaysWantOwnTabBar()
18603
// - DockContextBindNodeToWindow()
18604
// - BeginDocked()
18605
// - BeginDockableDragDropSource()
18606
// - BeginDockableDragDropTarget()
18607
//-----------------------------------------------------------------------------
18608
18609
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18610
77.3k
{
18611
77.3k
    ImGuiContext& g = *GImGui;
18612
77.3k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18613
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18614
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18615
0
                return true;
18616
77.3k
    return false;
18617
77.3k
}
18618
18619
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18620
0
{
18621
0
    ImGuiContext& g = *ctx;
18622
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18623
0
    IM_ASSERT(window->DockNode == NULL);
18624
18625
    // We should not be docking into a split node (SetWindowDock should avoid this)
18626
0
    if (node && node->IsSplitNode())
18627
0
    {
18628
0
        DockContextProcessUndockWindow(ctx, window);
18629
0
        return NULL;
18630
0
    }
18631
18632
    // Create node
18633
0
    if (node == NULL)
18634
0
    {
18635
0
        node = DockContextAddNode(ctx, window->DockId);
18636
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18637
0
        node->LastFrameAlive = g.FrameCount;
18638
0
    }
18639
18640
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18641
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18642
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18643
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18644
0
    if (!node->IsVisible)
18645
0
    {
18646
0
        ImGuiDockNode* ancestor_node = node;
18647
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18648
0
            ancestor_node = ancestor_node->ParentNode;
18649
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18650
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18651
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18652
0
    }
18653
18654
    // Add window to node
18655
0
    bool node_was_visible = node->IsVisible;
18656
0
    DockNodeAddWindow(node, window, true);
18657
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18658
0
    IM_ASSERT(node == window->DockNode);
18659
0
    return node;
18660
0
}
18661
18662
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18663
0
{
18664
0
    ImGuiContext* ctx = GImGui;
18665
0
    ImGuiContext& g = *ctx;
18666
18667
    // Clear fields ahead so most early-out paths don't have to do it
18668
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18669
18670
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18671
0
    if (auto_dock_node)
18672
0
    {
18673
0
        if (window->DockId == 0)
18674
0
        {
18675
0
            IM_ASSERT(window->DockNode == NULL);
18676
0
            window->DockId = DockContextGenNodeID(ctx);
18677
0
        }
18678
0
    }
18679
0
    else
18680
0
    {
18681
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18682
0
        bool want_undock = false;
18683
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18684
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18685
0
        if (want_undock)
18686
0
        {
18687
0
            DockContextProcessUndockWindow(ctx, window);
18688
0
            return;
18689
0
        }
18690
0
    }
18691
18692
    // Bind to our dock node
18693
0
    ImGuiDockNode* node = window->DockNode;
18694
0
    if (node != NULL)
18695
0
        IM_ASSERT(window->DockId == node->ID);
18696
0
    if (window->DockId != 0 && node == NULL)
18697
0
    {
18698
0
        node = DockContextBindNodeToWindow(ctx, window);
18699
0
        if (node == NULL)
18700
0
            return;
18701
0
    }
18702
18703
#if 0
18704
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18705
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18706
    {
18707
        DockContextProcessUndockWindow(ctx, window);
18708
        return;
18709
    }
18710
#endif
18711
18712
    // Undock if our dockspace node disappeared
18713
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18714
0
    if (node->LastFrameAlive < g.FrameCount)
18715
0
    {
18716
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18717
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18718
0
        if (root_node->LastFrameAlive < g.FrameCount)
18719
0
            DockContextProcessUndockWindow(ctx, window);
18720
0
        else
18721
0
            window->DockIsActive = true;
18722
0
        return;
18723
0
    }
18724
18725
    // Store style overrides
18726
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18727
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18728
18729
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18730
    // and never create neither a host window neither a tab bar.
18731
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18732
0
    if (node->HostWindow == NULL)
18733
0
    {
18734
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18735
0
            window->DockIsActive = true;
18736
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
18737
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18738
0
        return;
18739
0
    }
18740
18741
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18742
0
    IM_ASSERT(node->HostWindow);
18743
0
    IM_ASSERT(node->IsLeafNode());
18744
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18745
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18746
18747
    // Undock if we are submitted earlier than the host window
18748
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18749
0
    {
18750
0
        DockContextProcessUndockWindow(ctx, window);
18751
0
        return;
18752
0
    }
18753
18754
    // Position/Size window
18755
0
    SetNextWindowPos(node->Pos);
18756
0
    SetNextWindowSize(node->Size);
18757
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18758
0
    window->DockIsActive = true;
18759
0
    window->DockNodeIsVisible = true;
18760
0
    window->DockTabIsVisible = false;
18761
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18762
0
        return;
18763
18764
    // When the window is selected we mark it as visible.
18765
0
    if (node->VisibleWindow == window)
18766
0
        window->DockTabIsVisible = true;
18767
18768
    // Update window flag
18769
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18770
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
18771
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
18772
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18773
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18774
0
    else
18775
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18776
18777
    // Save new dock order only if the window has been visible once already
18778
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18779
0
    if (node->TabBar && window->WasActive)
18780
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18781
18782
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18783
0
        *p_open = false;
18784
18785
    // Update ChildId to allow returning from Child to Parent with Escape
18786
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18787
0
    window->ChildId = parent_window->GetID(window->Name);
18788
0
}
18789
18790
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18791
0
{
18792
0
    ImGuiContext& g = *GImGui;
18793
0
    IM_ASSERT(g.ActiveId == window->MoveId);
18794
0
    IM_ASSERT(g.MovingWindow == window);
18795
0
    IM_ASSERT(g.CurrentWindow == window);
18796
18797
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
18798
0
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
18799
0
    {
18800
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
18801
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
18802
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
18803
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
18804
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
18805
0
        return;
18806
0
    }
18807
18808
0
    g.LastItemData.ID = window->MoveId;
18809
0
    window = window->RootWindowDockTree;
18810
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18811
0
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18812
0
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18813
0
    {
18814
0
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18815
0
        EndDragDropSource();
18816
18817
        // Store style overrides
18818
0
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18819
0
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18820
0
    }
18821
0
}
18822
18823
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18824
0
{
18825
0
    ImGuiContext* ctx = GImGui;
18826
0
    ImGuiContext& g = *ctx;
18827
18828
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18829
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18830
0
    if (!g.DragDropActive)
18831
0
        return;
18832
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18833
0
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18834
0
        return;
18835
18836
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18837
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18838
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18839
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18840
0
    {
18841
0
        EndDragDropTarget();
18842
0
        return;
18843
0
    }
18844
18845
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18846
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18847
0
    {
18848
        // Select target node
18849
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18850
0
        bool dock_into_floating_window = false;
18851
0
        ImGuiDockNode* node = NULL;
18852
0
        if (window->DockNodeAsHost)
18853
0
        {
18854
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18855
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18856
18857
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18858
            // In this case we need to fallback into any leaf mode, possibly the central node.
18859
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18860
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18861
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18862
0
        }
18863
0
        else
18864
0
        {
18865
0
            if (window->DockNode)
18866
0
                node = window->DockNode;
18867
0
            else
18868
0
                dock_into_floating_window = true; // Dock into a regular window
18869
0
        }
18870
18871
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18872
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18873
18874
        // Preview docking request and find out split direction/ratio
18875
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18876
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18877
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18878
0
        {
18879
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18880
0
            ImGuiDockPreviewData split_inner;
18881
0
            ImGuiDockPreviewData split_outer;
18882
0
            ImGuiDockPreviewData* split_data = &split_inner;
18883
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18884
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18885
0
                {
18886
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18887
0
                    if (split_outer.IsSplitDirExplicit)
18888
0
                        split_data = &split_outer;
18889
0
                }
18890
0
            if (!node || node->IsLeafNode())
18891
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18892
0
            if (split_data == &split_outer)
18893
0
                split_inner.IsDropAllowed = false;
18894
18895
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18896
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18897
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18898
18899
            // Queue docking request
18900
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18901
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18902
0
        }
18903
0
    }
18904
0
    EndDragDropTarget();
18905
0
}
18906
18907
//-----------------------------------------------------------------------------
18908
// Docking: Settings
18909
//-----------------------------------------------------------------------------
18910
// - DockSettingsRenameNodeReferences()
18911
// - DockSettingsRemoveNodeReferences()
18912
// - DockSettingsFindNodeSettings()
18913
// - DockSettingsHandler_ApplyAll()
18914
// - DockSettingsHandler_ReadOpen()
18915
// - DockSettingsHandler_ReadLine()
18916
// - DockSettingsHandler_DockNodeToSettings()
18917
// - DockSettingsHandler_WriteAll()
18918
//-----------------------------------------------------------------------------
18919
18920
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18921
0
{
18922
0
    ImGuiContext& g = *GImGui;
18923
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18924
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18925
0
    {
18926
0
        ImGuiWindow* window = g.Windows[window_n];
18927
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18928
0
            window->DockId = new_node_id;
18929
0
    }
18930
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18931
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18932
0
        if (settings->DockId == old_node_id)
18933
0
            settings->DockId = new_node_id;
18934
0
}
18935
18936
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18937
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18938
0
{
18939
0
    ImGuiContext& g = *GImGui;
18940
0
    int found = 0;
18941
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18942
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18943
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18944
0
            if (settings->DockId == node_ids[node_n])
18945
0
            {
18946
0
                settings->DockId = 0;
18947
0
                settings->DockOrder = -1;
18948
0
                if (++found < node_ids_count)
18949
0
                    break;
18950
0
                return;
18951
0
            }
18952
0
}
18953
18954
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18955
0
{
18956
    // FIXME-OPT
18957
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18958
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18959
0
        if (dc->NodesSettings[n].ID == id)
18960
0
            return &dc->NodesSettings[n];
18961
0
    return NULL;
18962
0
}
18963
18964
// Clear settings data
18965
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18966
0
{
18967
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18968
0
    dc->NodesSettings.clear();
18969
0
    DockContextClearNodes(ctx, 0, true);
18970
0
}
18971
18972
// Recreate nodes based on settings data
18973
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18974
0
{
18975
    // Prune settings at boot time only
18976
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18977
0
    if (ctx->Windows.Size == 0)
18978
0
        DockContextPruneUnusedSettingsNodes(ctx);
18979
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18980
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18981
0
}
18982
18983
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18984
0
{
18985
0
    if (strcmp(name, "Data") != 0)
18986
0
        return NULL;
18987
0
    return (void*)1;
18988
0
}
18989
18990
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18991
0
{
18992
0
    char c = 0;
18993
0
    int x = 0, y = 0;
18994
0
    int r = 0;
18995
18996
    // Parsing, e.g.
18997
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18998
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18999
    // Important: this code expect currently fields in a fixed order.
19000
0
    ImGuiDockNodeSettings node;
19001
0
    line = ImStrSkipBlank(line);
19002
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19003
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19004
0
    else return;
19005
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19006
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19007
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19008
0
    if (node.ParentNodeId == 0)
19009
0
    {
19010
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19011
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19012
0
    }
19013
0
    else
19014
0
    {
19015
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19016
0
    }
19017
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19018
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19019
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19020
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19021
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19022
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19023
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19024
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19025
0
    if (node.ParentNodeId != 0)
19026
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19027
0
            node.Depth = parent_settings->Depth + 1;
19028
0
    ctx->DockContext.NodesSettings.push_back(node);
19029
0
}
19030
19031
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19032
0
{
19033
0
    ImGuiDockNodeSettings node_settings;
19034
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19035
0
    node_settings.ID = node->ID;
19036
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19037
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19038
0
    node_settings.SelectedTabId = node->SelectedTabId;
19039
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19040
0
    node_settings.Depth = (char)depth;
19041
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19042
0
    node_settings.Pos = ImVec2ih(node->Pos);
19043
0
    node_settings.Size = ImVec2ih(node->Size);
19044
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19045
0
    dc->NodesSettings.push_back(node_settings);
19046
0
    if (node->ChildNodes[0])
19047
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19048
0
    if (node->ChildNodes[1])
19049
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19050
0
}
19051
19052
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19053
0
{
19054
0
    ImGuiContext& g = *ctx;
19055
0
    ImGuiDockContext* dc = &ctx->DockContext;
19056
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19057
0
        return;
19058
19059
    // Gather settings data
19060
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19061
0
    dc->NodesSettings.resize(0);
19062
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19063
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19064
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19065
0
            if (node->IsRootNode())
19066
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19067
19068
0
    int max_depth = 0;
19069
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19070
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19071
19072
    // Write to text buffer
19073
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19074
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19075
0
    {
19076
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19077
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19078
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19079
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19080
0
        if (node_settings->ParentNodeId)
19081
0
        {
19082
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19083
0
        }
19084
0
        else
19085
0
        {
19086
0
            if (node_settings->ParentWindowId)
19087
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19088
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19089
0
        }
19090
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19091
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19092
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19093
0
            buf->appendf(" NoResize=1");
19094
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19095
0
            buf->appendf(" CentralNode=1");
19096
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19097
0
            buf->appendf(" NoTabBar=1");
19098
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19099
0
            buf->appendf(" HiddenTabBar=1");
19100
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19101
0
            buf->appendf(" NoWindowMenuButton=1");
19102
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19103
0
            buf->appendf(" NoCloseButton=1");
19104
0
        if (node_settings->SelectedTabId)
19105
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19106
19107
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19108
0
        if (g.IO.ConfigDebugIniSettings)
19109
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19110
0
            {
19111
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19112
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19113
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19114
                // Iterate settings so we can give info about windows that didn't exist during the session.
19115
0
                int contains_window = 0;
19116
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19117
0
                    if (settings->DockId == node_settings->ID)
19118
0
                    {
19119
0
                        if (contains_window++ == 0)
19120
0
                            buf->appendf(" ; contains ");
19121
0
                        buf->appendf("'%s' ", settings->GetName());
19122
0
                    }
19123
0
            }
19124
19125
0
        buf->appendf("\n");
19126
0
    }
19127
0
    buf->appendf("\n");
19128
0
}
19129
19130
19131
//-----------------------------------------------------------------------------
19132
// [SECTION] PLATFORM DEPENDENT HELPERS
19133
//-----------------------------------------------------------------------------
19134
19135
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19136
19137
#ifdef _MSC_VER
19138
#pragma comment(lib, "user32")
19139
#pragma comment(lib, "kernel32")
19140
#endif
19141
19142
// Win32 clipboard implementation
19143
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19144
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19145
{
19146
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19147
    g.ClipboardHandlerData.clear();
19148
    if (!::OpenClipboard(NULL))
19149
        return NULL;
19150
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19151
    if (wbuf_handle == NULL)
19152
    {
19153
        ::CloseClipboard();
19154
        return NULL;
19155
    }
19156
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19157
    {
19158
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19159
        g.ClipboardHandlerData.resize(buf_len);
19160
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19161
    }
19162
    ::GlobalUnlock(wbuf_handle);
19163
    ::CloseClipboard();
19164
    return g.ClipboardHandlerData.Data;
19165
}
19166
19167
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19168
{
19169
    if (!::OpenClipboard(NULL))
19170
        return;
19171
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19172
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19173
    if (wbuf_handle == NULL)
19174
    {
19175
        ::CloseClipboard();
19176
        return;
19177
    }
19178
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19179
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19180
    ::GlobalUnlock(wbuf_handle);
19181
    ::EmptyClipboard();
19182
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19183
        ::GlobalFree(wbuf_handle);
19184
    ::CloseClipboard();
19185
}
19186
19187
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19188
19189
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19190
static PasteboardRef main_clipboard = 0;
19191
19192
// OSX clipboard implementation
19193
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19194
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19195
{
19196
    if (!main_clipboard)
19197
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19198
    PasteboardClear(main_clipboard);
19199
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19200
    if (cf_data)
19201
    {
19202
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19203
        CFRelease(cf_data);
19204
    }
19205
}
19206
19207
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19208
{
19209
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19210
    if (!main_clipboard)
19211
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19212
    PasteboardSynchronize(main_clipboard);
19213
19214
    ItemCount item_count = 0;
19215
    PasteboardGetItemCount(main_clipboard, &item_count);
19216
    for (ItemCount i = 0; i < item_count; i++)
19217
    {
19218
        PasteboardItemID item_id = 0;
19219
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19220
        CFArrayRef flavor_type_array = 0;
19221
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19222
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19223
        {
19224
            CFDataRef cf_data;
19225
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19226
            {
19227
                g.ClipboardHandlerData.clear();
19228
                int length = (int)CFDataGetLength(cf_data);
19229
                g.ClipboardHandlerData.resize(length + 1);
19230
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19231
                g.ClipboardHandlerData[length] = 0;
19232
                CFRelease(cf_data);
19233
                return g.ClipboardHandlerData.Data;
19234
            }
19235
        }
19236
    }
19237
    return NULL;
19238
}
19239
19240
#else
19241
19242
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19243
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19244
0
{
19245
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19246
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19247
0
}
19248
19249
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19250
0
{
19251
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19252
0
    g.ClipboardHandlerData.clear();
19253
0
    const char* text_end = text + strlen(text);
19254
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
19255
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
19256
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
19257
0
}
19258
19259
#endif
19260
19261
// Win32 API IME support (for Asian languages, etc.)
19262
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
19263
19264
#include <imm.h>
19265
#ifdef _MSC_VER
19266
#pragma comment(lib, "imm32")
19267
#endif
19268
19269
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
19270
{
19271
    // Notify OS Input Method Editor of text input position
19272
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
19273
    if (hwnd == 0)
19274
        return;
19275
19276
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
19277
    if (HIMC himc = ::ImmGetContext(hwnd))
19278
    {
19279
        COMPOSITIONFORM composition_form = {};
19280
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19281
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19282
        composition_form.dwStyle = CFS_FORCE_POSITION;
19283
        ::ImmSetCompositionWindow(himc, &composition_form);
19284
        CANDIDATEFORM candidate_form = {};
19285
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19286
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19287
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19288
        ::ImmSetCandidateWindow(himc, &candidate_form);
19289
        ::ImmReleaseContext(hwnd, himc);
19290
    }
19291
}
19292
19293
#else
19294
19295
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19296
19297
#endif
19298
19299
//-----------------------------------------------------------------------------
19300
// [SECTION] METRICS/DEBUGGER WINDOW
19301
//-----------------------------------------------------------------------------
19302
// - RenderViewportThumbnail() [Internal]
19303
// - RenderViewportsThumbnails() [Internal]
19304
// - DebugTextEncoding()
19305
// - MetricsHelpMarker() [Internal]
19306
// - ShowFontAtlas() [Internal]
19307
// - ShowMetricsWindow()
19308
// - DebugNodeColumns() [Internal]
19309
// - DebugNodeDockNode() [Internal]
19310
// - DebugNodeDrawList() [Internal]
19311
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19312
// - DebugNodeFont() [Internal]
19313
// - DebugNodeFontGlyph() [Internal]
19314
// - DebugNodeStorage() [Internal]
19315
// - DebugNodeTabBar() [Internal]
19316
// - DebugNodeViewport() [Internal]
19317
// - DebugNodeWindow() [Internal]
19318
// - DebugNodeWindowSettings() [Internal]
19319
// - DebugNodeWindowsList() [Internal]
19320
// - DebugNodeWindowsListByBeginStackParent() [Internal]
19321
//-----------------------------------------------------------------------------
19322
19323
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19324
19325
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19326
0
{
19327
0
    ImGuiContext& g = *GImGui;
19328
0
    ImGuiWindow* window = g.CurrentWindow;
19329
19330
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
19331
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
19332
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19333
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19334
0
    for (ImGuiWindow* thumb_window : g.Windows)
19335
0
    {
19336
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19337
0
            continue;
19338
0
        if (thumb_window->Viewport != viewport)
19339
0
            continue;
19340
19341
0
        ImRect thumb_r = thumb_window->Rect();
19342
0
        ImRect title_r = thumb_window->TitleBarRect();
19343
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
19344
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
19345
0
        thumb_r.ClipWithFull(bb);
19346
0
        title_r.ClipWithFull(bb);
19347
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19348
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19349
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19350
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19351
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19352
0
    }
19353
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19354
0
}
19355
19356
static void RenderViewportsThumbnails()
19357
0
{
19358
0
    ImGuiContext& g = *GImGui;
19359
0
    ImGuiWindow* window = g.CurrentWindow;
19360
19361
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
19362
0
    float SCALE = 1.0f / 8.0f;
19363
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19364
0
    for (ImGuiViewportP* viewport : g.Viewports)
19365
0
        bb_full.Add(viewport->GetMainRect());
19366
0
    ImVec2 p = window->DC.CursorPos;
19367
0
    ImVec2 off = p - bb_full.Min * SCALE;
19368
0
    for (ImGuiViewportP* viewport : g.Viewports)
19369
0
    {
19370
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19371
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19372
0
    }
19373
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
19374
0
}
19375
19376
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19377
0
{
19378
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19379
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19380
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
19381
0
}
19382
19383
// Draw an arbitrary US keyboard layout to visualize translated keys
19384
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19385
0
{
19386
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
19387
0
    const float  key_rounding = 3.0f;
19388
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
19389
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
19390
0
    const float  key_face_rounding = 2.0f;
19391
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
19392
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19393
0
    const float  key_row_offset = 9.0f;
19394
19395
0
    ImVec2 board_min = GetCursorScreenPos();
19396
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19397
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19398
19399
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19400
0
    const KeyLayoutData keys_to_display[] =
19401
0
    {
19402
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19403
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19404
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19405
0
    };
19406
19407
    // Elements rendered manually via ImDrawList API are not clipped automatically.
19408
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19409
0
    Dummy(board_max - board_min);
19410
0
    if (!IsItemVisible())
19411
0
        return;
19412
0
    draw_list->PushClipRect(board_min, board_max, true);
19413
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19414
0
    {
19415
0
        const KeyLayoutData* key_data = &keys_to_display[n];
19416
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19417
0
        ImVec2 key_max = key_min + key_size;
19418
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19419
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19420
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19421
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19422
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19423
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19424
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19425
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19426
0
        if (IsKeyDown(key_data->Key))
19427
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19428
0
    }
19429
0
    draw_list->PopClipRect();
19430
0
}
19431
19432
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19433
void ImGui::DebugTextEncoding(const char* str)
19434
0
{
19435
0
    Text("Text: \"%s\"", str);
19436
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19437
0
        return;
19438
0
    TableSetupColumn("Offset");
19439
0
    TableSetupColumn("UTF-8");
19440
0
    TableSetupColumn("Glyph");
19441
0
    TableSetupColumn("Codepoint");
19442
0
    TableHeadersRow();
19443
0
    for (const char* p = str; *p != 0; )
19444
0
    {
19445
0
        unsigned int c;
19446
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19447
0
        TableNextColumn();
19448
0
        Text("%d", (int)(p - str));
19449
0
        TableNextColumn();
19450
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19451
0
        {
19452
0
            if (byte_index > 0)
19453
0
                SameLine();
19454
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19455
0
        }
19456
0
        TableNextColumn();
19457
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19458
0
            TextUnformatted(p, p + c_utf8_len);
19459
0
        else
19460
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19461
0
        TableNextColumn();
19462
0
        Text("U+%04X", (int)c);
19463
0
        p += c_utf8_len;
19464
0
    }
19465
0
    EndTable();
19466
0
}
19467
19468
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19469
static void MetricsHelpMarker(const char* desc)
19470
0
{
19471
0
    ImGui::TextDisabled("(?)");
19472
0
    if (ImGui::BeginItemTooltip())
19473
0
    {
19474
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19475
0
        ImGui::TextUnformatted(desc);
19476
0
        ImGui::PopTextWrapPos();
19477
0
        ImGui::EndTooltip();
19478
0
    }
19479
0
}
19480
19481
// [DEBUG] List fonts in a font atlas and display its texture
19482
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19483
0
{
19484
0
    for (ImFont* font : atlas->Fonts)
19485
0
    {
19486
0
        PushID(font);
19487
0
        DebugNodeFont(font);
19488
0
        PopID();
19489
0
    }
19490
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19491
0
    {
19492
0
        ImGuiContext& g = *GImGui;
19493
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19494
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19495
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19496
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19497
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19498
0
        TreePop();
19499
0
    }
19500
0
}
19501
19502
void ImGui::ShowMetricsWindow(bool* p_open)
19503
0
{
19504
0
    ImGuiContext& g = *GImGui;
19505
0
    ImGuiIO& io = g.IO;
19506
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19507
0
    if (cfg->ShowDebugLog)
19508
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19509
0
    if (cfg->ShowIDStackTool)
19510
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
19511
19512
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19513
0
    {
19514
0
        End();
19515
0
        return;
19516
0
    }
19517
19518
    // Basic info
19519
0
    Text("Dear ImGui %s", GetVersion());
19520
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19521
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19522
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
19523
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19524
19525
0
    Separator();
19526
19527
    // Debugging enums
19528
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19529
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19530
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19531
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19532
0
    if (cfg->ShowWindowsRectsType < 0)
19533
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19534
0
    if (cfg->ShowTablesRectsType < 0)
19535
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19536
19537
0
    struct Funcs
19538
0
    {
19539
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19540
0
        {
19541
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19542
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19543
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19544
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19545
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19546
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19547
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19548
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19549
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19550
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19551
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
19552
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
19553
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19554
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19555
0
            IM_ASSERT(0);
19556
0
            return ImRect();
19557
0
        }
19558
19559
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19560
0
        {
19561
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19562
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19563
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19564
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19565
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19566
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19567
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19568
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19569
0
            IM_ASSERT(0);
19570
0
            return ImRect();
19571
0
        }
19572
0
    };
19573
19574
    // Tools
19575
0
    if (TreeNode("Tools"))
19576
0
    {
19577
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
19578
0
        SameLine();
19579
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
19580
0
        if (show_encoding_viewer)
19581
0
        {
19582
0
            static char buf[100] = "";
19583
0
            SetNextItemWidth(-FLT_MIN);
19584
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
19585
0
            if (buf[0] != 0)
19586
0
                DebugTextEncoding(buf);
19587
0
            TreePop();
19588
0
        }
19589
19590
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19591
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19592
0
            DebugStartItemPicker();
19593
0
        SameLine();
19594
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19595
19596
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19597
0
        SameLine();
19598
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19599
19600
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
19601
0
        SameLine();
19602
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
19603
19604
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19605
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19606
0
        SameLine();
19607
0
        SetNextItemWidth(GetFontSize() * 12);
19608
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19609
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19610
0
        {
19611
0
            BulletText("'%s':", g.NavWindow->Name);
19612
0
            Indent();
19613
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19614
0
            {
19615
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19616
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19617
0
            }
19618
0
            Unindent();
19619
0
        }
19620
19621
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19622
0
        SameLine();
19623
0
        SetNextItemWidth(GetFontSize() * 12);
19624
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19625
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19626
0
        {
19627
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19628
0
            {
19629
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19630
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19631
0
                    continue;
19632
19633
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19634
0
                if (IsItemHovered())
19635
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19636
0
                Indent();
19637
0
                char buf[128];
19638
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19639
0
                {
19640
0
                    if (rect_n >= TRT_ColumnsRect)
19641
0
                    {
19642
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19643
0
                            continue;
19644
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19645
0
                        {
19646
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19647
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19648
0
                            Selectable(buf);
19649
0
                            if (IsItemHovered())
19650
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19651
0
                        }
19652
0
                    }
19653
0
                    else
19654
0
                    {
19655
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19656
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19657
0
                        Selectable(buf);
19658
0
                        if (IsItemHovered())
19659
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19660
0
                    }
19661
0
                }
19662
0
                Unindent();
19663
0
            }
19664
0
        }
19665
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
19666
19667
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19668
0
        SameLine();
19669
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19670
19671
0
        TreePop();
19672
0
    }
19673
19674
    // Windows
19675
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19676
0
    {
19677
        //SetNextItemOpen(true, ImGuiCond_Once);
19678
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19679
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19680
0
        if (TreeNode("By submission order (begin stack)"))
19681
0
        {
19682
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19683
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19684
0
            temp_buffer.resize(0);
19685
0
            for (ImGuiWindow* window : g.Windows)
19686
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
19687
0
                    temp_buffer.push_back(window);
19688
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19689
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19690
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19691
0
            TreePop();
19692
0
        }
19693
19694
0
        TreePop();
19695
0
    }
19696
19697
    // DrawLists
19698
0
    int drawlist_count = 0;
19699
0
    for (ImGuiViewportP* viewport : g.Viewports)
19700
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
19701
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19702
0
    {
19703
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19704
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19705
0
        for (ImGuiViewportP* viewport : g.Viewports)
19706
0
        {
19707
0
            bool viewport_has_drawlist = false;
19708
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
19709
0
            {
19710
0
                if (!viewport_has_drawlist)
19711
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19712
0
                viewport_has_drawlist = true;
19713
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
19714
0
            }
19715
0
        }
19716
0
        TreePop();
19717
0
    }
19718
19719
    // Viewports
19720
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19721
0
    {
19722
0
        Indent(GetTreeNodeToLabelSpacing());
19723
0
        RenderViewportsThumbnails();
19724
0
        Unindent(GetTreeNodeToLabelSpacing());
19725
19726
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19727
0
        SameLine();
19728
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19729
0
        if (open)
19730
0
        {
19731
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19732
0
            {
19733
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19734
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19735
0
                    i, mon.DpiScale * 100.0f,
19736
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19737
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19738
0
            }
19739
0
            TreePop();
19740
0
        }
19741
19742
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19743
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19744
0
        {
19745
0
            static ImVector<ImGuiViewportP*> viewports;
19746
0
            viewports.resize(g.Viewports.Size);
19747
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19748
0
            if (viewports.Size > 1)
19749
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
19750
0
            for (ImGuiViewportP* viewport : viewports)
19751
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
19752
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
19753
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
19754
0
                    viewport->Window ? viewport->Window->Name : "N/A");
19755
0
            TreePop();
19756
0
        }
19757
0
        for (ImGuiViewportP* viewport : g.Viewports)
19758
0
            DebugNodeViewport(viewport);
19759
0
        TreePop();
19760
0
    }
19761
19762
    // Details for Popups
19763
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19764
0
    {
19765
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
19766
0
        {
19767
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19768
0
            ImGuiWindow* window = popup_data.Window;
19769
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19770
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19771
0
                popup_data.BackupNavWindow ? popup_data.BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19772
0
        }
19773
0
        TreePop();
19774
0
    }
19775
19776
    // Details for TabBars
19777
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19778
0
    {
19779
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19780
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19781
0
            {
19782
0
                PushID(tab_bar);
19783
0
                DebugNodeTabBar(tab_bar, "TabBar");
19784
0
                PopID();
19785
0
            }
19786
0
        TreePop();
19787
0
    }
19788
19789
    // Details for Tables
19790
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19791
0
    {
19792
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19793
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19794
0
                DebugNodeTable(table);
19795
0
        TreePop();
19796
0
    }
19797
19798
    // Details for Fonts
19799
0
    ImFontAtlas* atlas = g.IO.Fonts;
19800
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19801
0
    {
19802
0
        ShowFontAtlas(atlas);
19803
0
        TreePop();
19804
0
    }
19805
19806
    // Details for InputText
19807
0
    if (TreeNode("InputText"))
19808
0
    {
19809
0
        DebugNodeInputTextState(&g.InputTextState);
19810
0
        TreePop();
19811
0
    }
19812
19813
    // Details for TypingSelect
19814
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
19815
0
    {
19816
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
19817
0
        TreePop();
19818
0
    }
19819
19820
    // Details for Docking
19821
0
#ifdef IMGUI_HAS_DOCK
19822
0
    if (TreeNode("Docking"))
19823
0
    {
19824
0
        static bool root_nodes_only = true;
19825
0
        ImGuiDockContext* dc = &g.DockContext;
19826
0
        Checkbox("List root nodes", &root_nodes_only);
19827
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19828
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19829
0
        SameLine();
19830
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19831
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19832
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19833
0
                if (!root_nodes_only || node->IsRootNode())
19834
0
                    DebugNodeDockNode(node, "Node");
19835
0
        TreePop();
19836
0
    }
19837
0
#endif // #ifdef IMGUI_HAS_DOCK
19838
19839
    // Settings
19840
0
    if (TreeNode("Settings"))
19841
0
    {
19842
0
        if (SmallButton("Clear"))
19843
0
            ClearIniSettings();
19844
0
        SameLine();
19845
0
        if (SmallButton("Save to memory"))
19846
0
            SaveIniSettingsToMemory();
19847
0
        SameLine();
19848
0
        if (SmallButton("Save to disk"))
19849
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19850
0
        SameLine();
19851
0
        if (g.IO.IniFilename)
19852
0
            Text("\"%s\"", g.IO.IniFilename);
19853
0
        else
19854
0
            TextUnformatted("<NULL>");
19855
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
19856
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19857
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19858
0
        {
19859
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
19860
0
                BulletText("\"%s\"", handler.TypeName);
19861
0
            TreePop();
19862
0
        }
19863
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19864
0
        {
19865
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19866
0
                DebugNodeWindowSettings(settings);
19867
0
            TreePop();
19868
0
        }
19869
19870
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19871
0
        {
19872
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19873
0
                DebugNodeTableSettings(settings);
19874
0
            TreePop();
19875
0
        }
19876
19877
0
#ifdef IMGUI_HAS_DOCK
19878
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19879
0
        {
19880
0
            ImGuiDockContext* dc = &g.DockContext;
19881
0
            Text("In SettingsWindows:");
19882
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19883
0
                if (settings->DockId != 0)
19884
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
19885
0
            Text("In SettingsNodes:");
19886
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19887
0
            {
19888
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19889
0
                const char* selected_tab_name = NULL;
19890
0
                if (settings->SelectedTabId)
19891
0
                {
19892
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19893
0
                        selected_tab_name = window->Name;
19894
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19895
0
                        selected_tab_name = window_settings->GetName();
19896
0
                }
19897
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19898
0
            }
19899
0
            TreePop();
19900
0
        }
19901
0
#endif // #ifdef IMGUI_HAS_DOCK
19902
19903
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19904
0
        {
19905
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19906
0
            TreePop();
19907
0
        }
19908
0
        TreePop();
19909
0
    }
19910
19911
    // Settings
19912
0
    if (TreeNode("Memory allocations"))
19913
0
    {
19914
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
19915
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
19916
0
        Text("Recent frames with allocations:");
19917
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
19918
0
        for (int n = buf_size - 1; n >= 0; n--)
19919
0
        {
19920
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
19921
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
19922
0
        }
19923
0
        TreePop();
19924
0
    }
19925
19926
0
    if (TreeNode("Inputs"))
19927
0
    {
19928
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19929
0
        {
19930
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19931
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19932
0
            Indent();
19933
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19934
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19935
#else
19936
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19937
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19938
#endif
19939
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19940
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19941
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19942
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19943
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19944
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19945
0
            Unindent();
19946
0
        }
19947
19948
0
        Text("MOUSE STATE");
19949
0
        {
19950
0
            Indent();
19951
0
            if (IsMousePosValid())
19952
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19953
0
            else
19954
0
                Text("Mouse pos: <INVALID>");
19955
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19956
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19957
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19958
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19959
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19960
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19961
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
19962
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
19963
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19964
0
            Unindent();
19965
0
        }
19966
19967
0
        Text("MOUSE WHEELING");
19968
0
        {
19969
0
            Indent();
19970
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19971
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19972
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19973
0
            Unindent();
19974
0
        }
19975
19976
0
        Text("KEY OWNERS");
19977
0
        {
19978
0
            Indent();
19979
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
19980
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19981
0
                {
19982
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
19983
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19984
0
                        continue;
19985
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19986
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19987
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19988
0
                }
19989
0
            EndChild();
19990
0
            Unindent();
19991
0
        }
19992
0
        Text("SHORTCUT ROUTING");
19993
0
        {
19994
0
            Indent();
19995
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
19996
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19997
0
                {
19998
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19999
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20000
0
                    {
20001
0
                        char key_chord_name[64];
20002
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20003
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
20004
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
20005
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20006
0
                        idx = routing_data->NextEntryIndex;
20007
0
                    }
20008
0
                }
20009
0
            EndChild();
20010
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20011
0
            Unindent();
20012
0
        }
20013
0
        TreePop();
20014
0
    }
20015
20016
0
    if (TreeNode("Internal state"))
20017
0
    {
20018
0
        Text("WINDOWING");
20019
0
        Indent();
20020
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20021
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20022
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20023
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20024
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20025
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20026
0
        Unindent();
20027
20028
0
        Text("ITEMS");
20029
0
        Indent();
20030
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20031
0
        DebugLocateItemOnHover(g.ActiveId);
20032
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20033
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20034
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20035
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20036
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20037
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20038
0
        Unindent();
20039
20040
0
        Text("NAV,FOCUS");
20041
0
        Indent();
20042
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20043
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20044
0
        DebugLocateItemOnHover(g.NavId);
20045
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20046
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20047
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20048
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20049
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20050
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20051
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20052
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20053
0
        Unindent();
20054
20055
0
        TreePop();
20056
0
    }
20057
20058
    // Overlay: Display windows Rectangles and Begin Order
20059
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20060
0
    {
20061
0
        for (ImGuiWindow* window : g.Windows)
20062
0
        {
20063
0
            if (!window->WasActive)
20064
0
                continue;
20065
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20066
0
            if (cfg->ShowWindowsRects)
20067
0
            {
20068
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20069
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20070
0
            }
20071
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20072
0
            {
20073
0
                char buf[32];
20074
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20075
0
                float font_size = GetFontSize();
20076
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20077
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20078
0
            }
20079
0
        }
20080
0
    }
20081
20082
    // Overlay: Display Tables Rectangles
20083
0
    if (cfg->ShowTablesRects)
20084
0
    {
20085
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20086
0
        {
20087
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20088
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20089
0
                continue;
20090
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20091
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20092
0
            {
20093
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20094
0
                {
20095
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20096
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20097
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20098
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20099
0
                }
20100
0
            }
20101
0
            else
20102
0
            {
20103
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20104
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20105
0
            }
20106
0
        }
20107
0
    }
20108
20109
0
#ifdef IMGUI_HAS_DOCK
20110
    // Overlay: Display Docking info
20111
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
20112
0
    {
20113
0
        char buf[64] = "";
20114
0
        char* p = buf;
20115
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
20116
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
20117
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
20118
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
20119
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
20120
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
20121
0
        int depth = DockNodeGetDepth(node);
20122
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
20123
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
20124
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
20125
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
20126
0
    }
20127
0
#endif // #ifdef IMGUI_HAS_DOCK
20128
20129
0
    End();
20130
0
}
20131
20132
// [DEBUG] Display contents of Columns
20133
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
20134
0
{
20135
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
20136
0
        return;
20137
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
20138
0
    for (ImGuiOldColumnData& column : columns->Columns)
20139
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
20140
0
    TreePop();
20141
0
}
20142
20143
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
20144
0
{
20145
0
    using namespace ImGui;
20146
0
    PushID(label);
20147
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
20148
0
    Text("%s:", label);
20149
0
    if (!enabled)
20150
0
        BeginDisabled();
20151
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
20152
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
20153
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
20154
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
20155
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
20156
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
20157
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
20158
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
20159
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
20160
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
20161
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
20162
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
20163
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
20164
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
20165
0
    if (!enabled)
20166
0
        EndDisabled();
20167
0
    PopStyleVar();
20168
0
    PopID();
20169
0
}
20170
20171
// [DEBUG] Display contents of ImDockNode
20172
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
20173
0
{
20174
0
    ImGuiContext& g = *GImGui;
20175
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
20176
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
20177
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20178
0
    bool open;
20179
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20180
0
    if (node->Windows.Size > 0)
20181
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20182
0
    else
20183
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
20184
0
    if (!is_alive) { PopStyleColor(); }
20185
0
    if (is_active && IsItemHovered())
20186
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
20187
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
20188
0
    if (open)
20189
0
    {
20190
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
20191
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
20192
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
20193
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
20194
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
20195
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
20196
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
20197
0
        BulletText("Misc:%s%s%s%s%s%s%s",
20198
0
            node->IsDockSpace() ? " IsDockSpace" : "",
20199
0
            node->IsCentralNode() ? " IsCentralNode" : "",
20200
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
20201
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
20202
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
20203
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
20204
0
        {
20205
0
            if (BeginTable("flags", 4))
20206
0
            {
20207
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
20208
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
20209
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
20210
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
20211
0
                EndTable();
20212
0
            }
20213
0
            TreePop();
20214
0
        }
20215
0
        if (node->ParentNode)
20216
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
20217
0
        if (node->ChildNodes[0])
20218
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
20219
0
        if (node->ChildNodes[1])
20220
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
20221
0
        if (node->TabBar)
20222
0
            DebugNodeTabBar(node->TabBar, "TabBar");
20223
0
        DebugNodeWindowsList(&node->Windows, "Windows");
20224
20225
0
        TreePop();
20226
0
    }
20227
0
}
20228
20229
// [DEBUG] Display contents of ImDrawList
20230
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
20231
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
20232
0
{
20233
0
    ImGuiContext& g = *GImGui;
20234
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20235
0
    int cmd_count = draw_list->CmdBuffer.Size;
20236
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
20237
0
        cmd_count--;
20238
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
20239
0
    if (draw_list == GetWindowDrawList())
20240
0
    {
20241
0
        SameLine();
20242
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
20243
0
        if (node_open)
20244
0
            TreePop();
20245
0
        return;
20246
0
    }
20247
20248
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
20249
0
    if (window && IsItemHovered() && fg_draw_list)
20250
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20251
0
    if (!node_open)
20252
0
        return;
20253
20254
0
    if (window && !window->WasActive)
20255
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
20256
20257
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
20258
0
    {
20259
0
        if (pcmd->UserCallback)
20260
0
        {
20261
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
20262
0
            continue;
20263
0
        }
20264
20265
0
        char buf[300];
20266
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
20267
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
20268
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
20269
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
20270
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
20271
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
20272
0
        if (!pcmd_node_open)
20273
0
            continue;
20274
20275
        // Calculate approximate coverage area (touched pixel count)
20276
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
20277
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
20278
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
20279
0
        float total_area = 0.0f;
20280
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
20281
0
        {
20282
0
            ImVec2 triangle[3];
20283
0
            for (int n = 0; n < 3; n++, idx_n++)
20284
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
20285
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
20286
0
        }
20287
20288
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20289
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20290
0
        Selectable(buf);
20291
0
        if (IsItemHovered() && fg_draw_list)
20292
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20293
20294
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20295
0
        ImGuiListClipper clipper;
20296
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20297
0
        while (clipper.Step())
20298
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20299
0
            {
20300
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20301
0
                ImVec2 triangle[3];
20302
0
                for (int n = 0; n < 3; n++, idx_i++)
20303
0
                {
20304
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20305
0
                    triangle[n] = v.pos;
20306
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20307
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20308
0
                }
20309
20310
0
                Selectable(buf, false);
20311
0
                if (fg_draw_list && IsItemHovered())
20312
0
                {
20313
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
20314
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20315
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20316
0
                    fg_draw_list->Flags = backup_flags;
20317
0
                }
20318
0
            }
20319
0
        TreePop();
20320
0
    }
20321
0
    TreePop();
20322
0
}
20323
20324
// [DEBUG] Display mesh/aabb of a ImDrawCmd
20325
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20326
0
{
20327
0
    IM_ASSERT(show_mesh || show_aabb);
20328
20329
    // Draw wire-frame version of all triangles
20330
0
    ImRect clip_rect = draw_cmd->ClipRect;
20331
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20332
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
20333
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20334
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20335
0
    {
20336
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20337
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20338
20339
0
        ImVec2 triangle[3];
20340
0
        for (int n = 0; n < 3; n++, idx_n++)
20341
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20342
0
        if (show_mesh)
20343
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20344
0
    }
20345
    // Draw bounding boxes
20346
0
    if (show_aabb)
20347
0
    {
20348
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20349
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20350
0
    }
20351
0
    out_draw_list->Flags = backup_flags;
20352
0
}
20353
20354
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20355
void ImGui::DebugNodeFont(ImFont* font)
20356
0
{
20357
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20358
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20359
0
    SameLine();
20360
0
    if (SmallButton("Set as default"))
20361
0
        GetIO().FontDefault = font;
20362
0
    if (!opened)
20363
0
        return;
20364
20365
    // Display preview text
20366
0
    PushFont(font);
20367
0
    Text("The quick brown fox jumps over the lazy dog");
20368
0
    PopFont();
20369
20370
    // Display details
20371
0
    SetNextItemWidth(GetFontSize() * 8);
20372
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20373
0
    SameLine(); MetricsHelpMarker(
20374
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
20375
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20376
0
        "You may oversample them to get some flexibility with scaling. "
20377
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20378
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20379
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20380
0
    char c_str[5];
20381
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20382
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20383
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20384
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20385
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20386
0
        if (font->ConfigData)
20387
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20388
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20389
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20390
20391
    // Display all glyphs of the fonts in separate pages of 256 characters
20392
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20393
0
    {
20394
0
        ImDrawList* draw_list = GetWindowDrawList();
20395
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20396
0
        const float cell_size = font->FontSize * 1;
20397
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
20398
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20399
0
        {
20400
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20401
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20402
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20403
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20404
0
            {
20405
0
                base += 4096 - 256;
20406
0
                continue;
20407
0
            }
20408
20409
0
            int count = 0;
20410
0
            for (unsigned int n = 0; n < 256; n++)
20411
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20412
0
                    count++;
20413
0
            if (count <= 0)
20414
0
                continue;
20415
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20416
0
                continue;
20417
20418
            // Draw a 16x16 grid of glyphs
20419
0
            ImVec2 base_pos = GetCursorScreenPos();
20420
0
            for (unsigned int n = 0; n < 256; n++)
20421
0
            {
20422
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20423
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20424
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20425
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20426
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20427
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20428
0
                if (!glyph)
20429
0
                    continue;
20430
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20431
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20432
0
                {
20433
0
                    DebugNodeFontGlyph(font, glyph);
20434
0
                    EndTooltip();
20435
0
                }
20436
0
            }
20437
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20438
0
            TreePop();
20439
0
        }
20440
0
        TreePop();
20441
0
    }
20442
0
    TreePop();
20443
0
}
20444
20445
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20446
0
{
20447
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20448
0
    Separator();
20449
0
    Text("Visible: %d", glyph->Visible);
20450
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20451
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20452
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20453
0
}
20454
20455
// [DEBUG] Display contents of ImGuiStorage
20456
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20457
0
{
20458
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20459
0
        return;
20460
0
    for (const ImGuiStorage::ImGuiStoragePair& p : storage->Data)
20461
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20462
0
    TreePop();
20463
0
}
20464
20465
// [DEBUG] Display contents of ImGuiTabBar
20466
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20467
0
{
20468
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20469
0
    char buf[256];
20470
0
    char* p = buf;
20471
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20472
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20473
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20474
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20475
0
    {
20476
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20477
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20478
0
    }
20479
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20480
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20481
0
    bool open = TreeNode(label, "%s", buf);
20482
0
    if (!is_active) { PopStyleColor(); }
20483
0
    if (is_active && IsItemHovered())
20484
0
    {
20485
0
        ImDrawList* draw_list = GetForegroundDrawList();
20486
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20487
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20488
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20489
0
    }
20490
0
    if (open)
20491
0
    {
20492
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20493
0
        {
20494
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20495
0
            PushID(tab);
20496
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20497
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20498
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20499
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20500
0
            PopID();
20501
0
        }
20502
0
        TreePop();
20503
0
    }
20504
0
}
20505
20506
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20507
0
{
20508
0
    SetNextItemOpen(true, ImGuiCond_Once);
20509
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
20510
0
    {
20511
0
        ImGuiWindowFlags flags = viewport->Flags;
20512
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20513
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20514
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20515
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20516
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20517
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20518
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20519
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20520
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20521
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20522
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20523
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20524
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20525
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20526
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20527
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20528
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20529
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20530
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20531
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20532
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20533
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20534
0
        TreePop();
20535
0
    }
20536
0
}
20537
20538
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
20539
0
{
20540
0
    if (window == NULL)
20541
0
    {
20542
0
        BulletText("%s: NULL", label);
20543
0
        return;
20544
0
    }
20545
20546
0
    ImGuiContext& g = *GImGui;
20547
0
    const bool is_active = window->WasActive;
20548
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20549
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20550
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
20551
0
    if (!is_active) { PopStyleColor(); }
20552
0
    if (IsItemHovered() && is_active)
20553
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20554
0
    if (!open)
20555
0
        return;
20556
20557
0
    if (window->MemoryCompacted)
20558
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
20559
20560
0
    ImGuiWindowFlags flags = window->Flags;
20561
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
20562
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
20563
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
20564
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
20565
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
20566
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
20567
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
20568
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
20569
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
20570
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
20571
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20572
0
    {
20573
0
        ImRect r = window->NavRectRel[layer];
20574
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
20575
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
20576
0
        else
20577
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
20578
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
20579
0
    }
20580
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
20581
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20582
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
20583
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
20584
20585
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
20586
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
20587
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
20588
0
    if (window->DockNode || window->DockNodeAsHost)
20589
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
20590
20591
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
20592
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
20593
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
20594
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
20595
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
20596
0
    {
20597
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
20598
0
            DebugNodeColumns(&columns);
20599
0
        TreePop();
20600
0
    }
20601
0
    DebugNodeStorage(&window->StateStorage, "Storage");
20602
0
    TreePop();
20603
0
}
20604
20605
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
20606
0
{
20607
0
    if (settings->WantDelete)
20608
0
        BeginDisabled();
20609
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
20610
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
20611
0
    if (settings->WantDelete)
20612
0
        EndDisabled();
20613
0
}
20614
20615
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
20616
0
{
20617
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
20618
0
        return;
20619
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
20620
0
    {
20621
0
        PushID((*windows)[i]);
20622
0
        DebugNodeWindow((*windows)[i], "Window");
20623
0
        PopID();
20624
0
    }
20625
0
    TreePop();
20626
0
}
20627
20628
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
20629
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
20630
0
{
20631
0
    for (int i = 0; i < windows_size; i++)
20632
0
    {
20633
0
        ImGuiWindow* window = windows[i];
20634
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
20635
0
            continue;
20636
0
        char buf[20];
20637
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
20638
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
20639
0
        DebugNodeWindow(window, buf);
20640
0
        Indent();
20641
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20642
0
        Unindent();
20643
0
    }
20644
0
}
20645
20646
//-----------------------------------------------------------------------------
20647
// [SECTION] DEBUG LOG WINDOW
20648
//-----------------------------------------------------------------------------
20649
20650
void ImGui::DebugLog(const char* fmt, ...)
20651
0
{
20652
0
    va_list args;
20653
0
    va_start(args, fmt);
20654
0
    DebugLogV(fmt, args);
20655
0
    va_end(args);
20656
0
}
20657
20658
void ImGui::DebugLogV(const char* fmt, va_list args)
20659
0
{
20660
0
    ImGuiContext& g = *GImGui;
20661
0
    const int old_size = g.DebugLogBuf.size();
20662
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20663
0
    g.DebugLogBuf.appendfv(fmt, args);
20664
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20665
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20666
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20667
#ifdef IMGUI_ENABLE_TEST_ENGINE
20668
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
20669
        IMGUI_TEST_ENGINE_LOG("%s", g.DebugLogBuf.begin() + old_size);
20670
#endif
20671
0
}
20672
20673
void ImGui::ShowDebugLogWindow(bool* p_open)
20674
0
{
20675
0
    ImGuiContext& g = *GImGui;
20676
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20677
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20678
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20679
0
    {
20680
0
        End();
20681
0
        return;
20682
0
    }
20683
20684
0
    CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20685
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20686
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20687
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20688
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20689
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20690
    //SameLine(); CheckboxFlags("Selection", &g.DebugLogFlags, ImGuiDebugLogFlags_EventSelection);
20691
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20692
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20693
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20694
20695
0
    if (SmallButton("Clear"))
20696
0
    {
20697
0
        g.DebugLogBuf.clear();
20698
0
        g.DebugLogIndex.clear();
20699
0
    }
20700
0
    SameLine();
20701
0
    if (SmallButton("Copy"))
20702
0
        SetClipboardText(g.DebugLogBuf.c_str());
20703
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20704
20705
0
    ImGuiListClipper clipper;
20706
0
    clipper.Begin(g.DebugLogIndex.size());
20707
0
    while (clipper.Step())
20708
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20709
0
        {
20710
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20711
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20712
0
            TextUnformatted(line_begin, line_end);
20713
0
            ImRect text_rect = g.LastItemData.Rect;
20714
0
            if (IsItemHovered())
20715
0
                for (const char* p = line_begin; p <= line_end - 10; p++)
20716
0
                {
20717
0
                    ImGuiID id = 0;
20718
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20719
0
                        continue;
20720
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20721
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20722
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20723
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20724
0
                        DebugLocateItemOnHover(id);
20725
0
                    p += 10;
20726
0
                }
20727
0
        }
20728
0
    if (GetScrollY() >= GetScrollMaxY())
20729
0
        SetScrollHereY(1.0f);
20730
0
    EndChild();
20731
20732
0
    End();
20733
0
}
20734
20735
//-----------------------------------------------------------------------------
20736
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
20737
//-----------------------------------------------------------------------------
20738
20739
// Draw a small cross at current CursorPos in current window's DrawList
20740
void ImGui::DebugDrawCursorPos(ImU32 col)
20741
0
{
20742
0
    ImGuiContext& g = *GImGui;
20743
0
    ImGuiWindow* window = g.CurrentWindow;
20744
0
    ImVec2 pos = window->DC.CursorPos;
20745
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
20746
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
20747
0
}
20748
20749
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
20750
void ImGui::DebugDrawLineExtents(ImU32 col)
20751
0
{
20752
0
    ImGuiContext& g = *GImGui;
20753
0
    ImGuiWindow* window = g.CurrentWindow;
20754
0
    float curr_x = window->DC.CursorPos.x;
20755
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
20756
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
20757
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
20758
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
20759
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
20760
0
}
20761
20762
// Draw last item rect in ForegroundDrawList (so it is always visible)
20763
void ImGui::DebugDrawItemRect(ImU32 col)
20764
0
{
20765
0
    ImGuiContext& g = *GImGui;
20766
0
    ImGuiWindow* window = g.CurrentWindow;
20767
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
20768
0
}
20769
20770
// [DEBUG] Locate item position/rectangle given an ID.
20771
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20772
20773
void ImGui::DebugLocateItem(ImGuiID target_id)
20774
0
{
20775
0
    ImGuiContext& g = *GImGui;
20776
0
    g.DebugLocateId = target_id;
20777
0
    g.DebugLocateFrames = 2;
20778
0
}
20779
20780
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20781
0
{
20782
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20783
0
        return;
20784
0
    ImGuiContext& g = *GImGui;
20785
0
    DebugLocateItem(target_id);
20786
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20787
0
}
20788
20789
void ImGui::DebugLocateItemResolveWithLastItem()
20790
0
{
20791
0
    ImGuiContext& g = *GImGui;
20792
0
    ImGuiLastItemData item_data = g.LastItemData;
20793
0
    g.DebugLocateId = 0;
20794
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20795
0
    ImRect r = item_data.Rect;
20796
0
    r.Expand(3.0f);
20797
0
    ImVec2 p1 = g.IO.MousePos;
20798
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20799
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20800
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20801
0
}
20802
20803
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20804
void ImGui::UpdateDebugToolItemPicker()
20805
25.7k
{
20806
25.7k
    ImGuiContext& g = *GImGui;
20807
25.7k
    g.DebugItemPickerBreakId = 0;
20808
25.7k
    if (!g.DebugItemPickerActive)
20809
25.7k
        return;
20810
20811
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20812
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20813
0
    if (IsKeyPressed(ImGuiKey_Escape))
20814
0
        g.DebugItemPickerActive = false;
20815
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20816
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20817
0
    {
20818
0
        g.DebugItemPickerBreakId = hovered_id;
20819
0
        g.DebugItemPickerActive = false;
20820
0
    }
20821
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20822
0
        if (change_mapping && IsMouseClicked(mouse_button))
20823
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20824
0
    SetNextWindowBgAlpha(0.70f);
20825
0
    if (!BeginTooltip())
20826
0
        return;
20827
0
    Text("HoveredId: 0x%08X", hovered_id);
20828
0
    Text("Press ESC to abort picking.");
20829
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20830
0
    if (change_mapping)
20831
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20832
0
    else
20833
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20834
0
    EndTooltip();
20835
0
}
20836
20837
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
20838
void ImGui::UpdateDebugToolStackQueries()
20839
25.7k
{
20840
25.7k
    ImGuiContext& g = *GImGui;
20841
25.7k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20842
20843
    // Clear hook when id stack tool is not visible
20844
25.7k
    g.DebugHookIdInfo = 0;
20845
25.7k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20846
25.7k
        return;
20847
20848
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20849
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20850
2
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20851
2
    if (tool->QueryId != query_id)
20852
0
    {
20853
0
        tool->QueryId = query_id;
20854
0
        tool->StackLevel = -1;
20855
0
        tool->Results.resize(0);
20856
0
    }
20857
2
    if (query_id == 0)
20858
2
        return;
20859
20860
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20861
0
    int stack_level = tool->StackLevel;
20862
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20863
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20864
0
            tool->StackLevel++;
20865
20866
    // Update hook
20867
0
    stack_level = tool->StackLevel;
20868
0
    if (stack_level == -1)
20869
0
        g.DebugHookIdInfo = query_id;
20870
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20871
0
    {
20872
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20873
0
        tool->Results[stack_level].QueryFrameCount++;
20874
0
    }
20875
0
}
20876
20877
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
20878
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20879
0
{
20880
0
    ImGuiContext& g = *GImGui;
20881
0
    ImGuiWindow* window = g.CurrentWindow;
20882
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20883
20884
    // Step 0: stack query
20885
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20886
0
    if (tool->StackLevel == -1)
20887
0
    {
20888
0
        tool->StackLevel++;
20889
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20890
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20891
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20892
0
        return;
20893
0
    }
20894
20895
    // Step 1+: query for individual level
20896
0
    IM_ASSERT(tool->StackLevel >= 0);
20897
0
    if (tool->StackLevel != window->IDStack.Size)
20898
0
        return;
20899
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20900
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20901
20902
0
    switch (data_type)
20903
0
    {
20904
0
    case ImGuiDataType_S32:
20905
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20906
0
        break;
20907
0
    case ImGuiDataType_String:
20908
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20909
0
        break;
20910
0
    case ImGuiDataType_Pointer:
20911
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20912
0
        break;
20913
0
    case ImGuiDataType_ID:
20914
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20915
0
            return;
20916
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20917
0
        break;
20918
0
    default:
20919
0
        IM_ASSERT(0);
20920
0
    }
20921
0
    info->QuerySuccess = true;
20922
0
    info->DataType = data_type;
20923
0
}
20924
20925
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20926
0
{
20927
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20928
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20929
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20930
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20931
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20932
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20933
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20934
0
        return (*buf = 0);
20935
#ifdef IMGUI_ENABLE_TEST_ENGINE
20936
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20937
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20938
#endif
20939
0
    return ImFormatString(buf, buf_size, "???");
20940
0
}
20941
20942
// ID Stack Tool: Display UI
20943
void ImGui::ShowIDStackToolWindow(bool* p_open)
20944
0
{
20945
0
    ImGuiContext& g = *GImGui;
20946
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20947
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20948
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20949
0
    {
20950
0
        End();
20951
0
        return;
20952
0
    }
20953
20954
    // Display hovered/active status
20955
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
20956
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20957
0
    const ImGuiID active_id = g.ActiveId;
20958
#ifdef IMGUI_ENABLE_TEST_ENGINE
20959
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20960
#else
20961
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20962
0
#endif
20963
0
    SameLine();
20964
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20965
20966
    // CTRL+C to copy path
20967
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20968
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20969
0
    SameLine();
20970
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20971
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20972
0
    {
20973
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20974
0
        char* p = g.TempBuffer.Data;
20975
0
        char* p_end = p + g.TempBuffer.Size;
20976
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20977
0
        {
20978
0
            *p++ = '/';
20979
0
            char level_desc[256];
20980
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20981
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20982
0
            {
20983
0
                if (level_desc[n] == '/')
20984
0
                    *p++ = '\\';
20985
0
                *p++ = level_desc[n];
20986
0
            }
20987
0
        }
20988
0
        *p = '\0';
20989
0
        SetClipboardText(g.TempBuffer.Data);
20990
0
    }
20991
20992
    // Display decorated stack
20993
0
    tool->LastActiveFrame = g.FrameCount;
20994
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20995
0
    {
20996
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20997
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20998
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20999
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
21000
0
        TableHeadersRow();
21001
0
        for (int n = 0; n < tool->Results.Size; n++)
21002
0
        {
21003
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
21004
0
            TableNextColumn();
21005
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
21006
0
            TableNextColumn();
21007
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
21008
0
            TextUnformatted(g.TempBuffer.Data);
21009
0
            TableNextColumn();
21010
0
            Text("0x%08X", info->ID);
21011
0
            if (n == tool->Results.Size - 1)
21012
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
21013
0
        }
21014
0
        EndTable();
21015
0
    }
21016
0
    End();
21017
0
}
21018
21019
#else
21020
21021
void ImGui::ShowMetricsWindow(bool*) {}
21022
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
21023
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
21024
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
21025
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
21026
void ImGui::DebugNodeFont(ImFont*) {}
21027
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
21028
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
21029
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
21030
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
21031
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
21032
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
21033
21034
void ImGui::DebugLog(const char*, ...) {}
21035
void ImGui::DebugLogV(const char*, va_list) {}
21036
void ImGui::ShowDebugLogWindow(bool*) {}
21037
void ImGui::ShowIDStackToolWindow(bool*) {}
21038
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
21039
void ImGui::UpdateDebugToolItemPicker() {}
21040
void ImGui::UpdateDebugToolStackQueries() {}
21041
21042
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
21043
21044
//-----------------------------------------------------------------------------
21045
21046
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
21047
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
21048
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
21049
#include "imgui_user.inl"
21050
#endif
21051
21052
//-----------------------------------------------------------------------------
21053
21054
#endif // #ifndef IMGUI_DISABLE